How to understand various snippets of setTimeout() function in JavaScript ?
Last Updated :
02 Jan, 2023
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()
Similar Reads
Using the function* Declaration in JavaScript
The function* declaration is used to define a generator that returns a Generator object. Generators are very powerful for asynchronous programming as they aim to resolve callback problems. In a generator, the yield keyword is used instead of return. The yield statement suspends the functionâs execut
2 min read
What is the difference between call and apply in JavaScript ?
JavaScript call() Method: It calls the method, taking the owner object as an argument. The keyword this refers to the 'owner' of the function or the object it belongs to. We can call a method that can be used on different objects. Syntax: object.objectMethod.call( objectInstance, arguments ) JavaScr
2 min read
How to find out the caller function in JavaScript?
In this article, we see the methods to find out the caller function in Javascript. Sometimes, the developer may want to modify how a function works on the basis of its caller function. To find out the caller function name, we will use the Function object's caller property. Property: Function.caller
1 min read
How to negate a predicate function in JavaScript ?
In this article, we will see how to negate a predicate function in JavaScript. Predicate functions are the ones that check the condition and return true and false based on the argument. Our task is to get the opposite of the predicate function. We follow the following method to get the desired resul
3 min read
How to iterate over a callback n times in JavaScript?
Given a callback function, we have to iterate over a callback n times. The callback is a function that is passed as an argument. To iterate over the callback function, we have to run the callback function n time.Here we have some common approaches:Table of ContentUsing recursion to iterate the n tim
4 min read
How to call function from it name stored in a string using JavaScript ?
In this article, we will call a function from the string stored in a variable. There are two methods to call a function from a string stored in a variable. Using window object methodUsing eval() method Note: The eval() method is older and is deprecated. Method 1: Using the window object. The window
2 min read
How to measure time taken by a function to execute using JavaScript ?
This article will show how to measure the time taken by a function to execute using Javascript. To measure the time taken by a function to execute we have three methods: Table of Content Using the Using Date ObjectUsing the performance.now() methodUsing the console.time() methodMethod 1: Using the U
3 min read
How to check a function is defined in JavaScript ?
In this article, we will check whether a function is defined or not in JavaScript. The JavaScript typeof operator is used to check whether the function is defined or not. JavaScript typeof OperatorThe typeof operator is used to find the type of a JavaScript variable. This operator returns the type o
2 min read
How to wait for a promise to finish before returning the variable of a function ?
Waiting for a promise to finish before returning a variable in a function is crucial when dealing with asynchronous operations in JavaScript, like fetching data from an API. Using async and await allows the function to pause execution until the promise resolves, ensuring reliable and expected result
3 min read
How to change the value of a global variable inside of a function using JavaScript ?
Pre-requisite: Global and Local variables in JavaScript Local Scope: Variables that are declared inside a function is called local variables and these are accessed only inside the function. Local variables are deleted when the function is completed. Global Scope: Global variables can be accessed fro
2 min read