When dealing with JavaScript, there will be times when you wish to run a function after a particular period of time. For this, we use setTimeout(), an asynchronous method that sets a timer, which then executes the function or specified piece of code once the timer expires. In this article, we will be exploring several code snippets on how setTimeout is used.
Syntax:
setTimeout(() => { // Your function which will execute after // 5000 milliseconds }, 5000);
We see the number 5000 refers to the milliseconds it will wait to execute the function. Inside the setTimeout() method, we declared a callback function that will execute after 5000 milliseconds.
Example 1: We can also pass our function in the following way:
Javascript
<script> const greetFunc = () => { console.log( 'Hello from GFG' ); }; //Greet after 5000 milliseconds setTimeout(greetFunc, 5000); </script> |
Output:
Hello from GFG
Example 2: Suppose our function takes parameters, then we can write the syntax in the following way:
Javascript
<script> const greetFunc = (name, company) => { console.log(`Hi ${name}, welcome to ${company}!`); }; setTimeout(greetFunc, 5000, 'Anom' , 'GeeksForGeeks' ); </script> |
Output:
Hi Anom, welcome to GeeksForGeeks!
We can see that the function props are passed after the timeout parameter.
Example 3: Now a question arises, what if we set the timer to 0 milliseconds? Let’s find out:
Javascript
<script> setTimeout(() => { console.log( 'Logging from 0ms wait timeout' ); }, 0); console.log( 'First' ); const randomFunction = () => { console.log( 'Some random function' ); }; randomFunction(); </script> |
Output:
First Some random function Logging from 0ms wait timeout
Explanation: We can see that even if the setTimeout() is declared earlier in the code with 0ms wait time, it will still execute at the end. This is because, despite having a delay of zero, setTimeout is queued and scheduled to run at the next available opportunity, not immediately. Because currently-running code must complete before queued functions are invoked.
Example 4: Let’s see, what will happen if we use setTimeout inside a loop: In the below function we are trying to console log a variable i after i milliseconds.
Javascript
<script> const print = () => { for ( var i = 0; i < 4; i++){ setTimeout(() => { console.log(i); }, i*1000); } } print(); </script> |
Output:
4 4 4 4
Explanation: If we execute the above code, we will expect it to print 0 1 2 3. But it will print 4 4 4 4, because each time the loop is run, it stores a reference to the same i variable in the memory space. To overcome this issue, if we change the variable type ‘var‘ to ‘let‘ which is a block scope, it will create a completely new copy of i at every loop iteration in the memory space. Thus the callback function inside the setTimeout forms a closure with the i variable at every iteration. To know more about closures follow this article: https://www.geeksforgeeks.org/closure-in-javascript/
Output after changing variable type ‘var’ to ‘let’ :
0 1 2 3
Example 5: But there may come sometime when we want to cancel a timeout that we had already planned. To deal with this we have a clearTimeout() method in JavaScript. Let’s see how we can use it:
Javascript
<script> const greetFunc = setTimeout(() => { console.log(`Hello from GeeksForGeeks`); }, 5000); clearTimeout(greetFunc); </script> |
Output:
//No output in console
No output is shown because we have canceled the setTimeout using clearTimeout()