This article shows you a complete understanding of the setTimeout() function and its uses in Javascript.
The setTimeout()
is a function available in the window object. The global setTimeout()
method sets a timer that executes a function or specified piece of code after specified milliseconds.
Let’s see a few examples of setTimeout() method below:-
Example1
Example2
Table of Contents
What is setTimeout()?
The setTimeout()
is a global method that executes a callback function once after a specified time of delays (in milliseconds).
Note: 1000 milliseconds = 1 second.
Syntax
var timeoutID = setTimeout(function, milliseconds, arg1, arg2, …);
Parameters
function –
A callback function to be executed after a specified delay time.
milliseconds [optional]-
The time, in milliseconds that the timer should wait before the specified function to be executed. This is an optional parameter. If this parameter is omitted, a value of 0 is used, meaning execute “immediately”.
arg1, arg2, … [optional]-
Additional arguments are passed through to the function specified by the function. These arguments are also optional.
Return value
The returned timeoutID
is a positive integer value that identifies the timer created by the call to setTimeout()
. This value can be passed to clearTimeout()
to cancel the timeout.
The setTimeout uses in Javascript
The followings are a few examples of using setTimeout method in javascript:
Example-1: Display an alert message after 2 seconds.
// an alert message will be displayed after 2 seconds
setTimeout(function(){
alert("Welcome to Javacodepoint");
}, 2000);
Example-2: Passing the additional parameters to setTimeout()
// Here an alert message will be displayed after 3 seconds
var dynamicValue=100;
setTimeout(function(arg1,arg2,arg3){
alert("Received parameters value :"+arg1+", " +arg2+", "+arg3);
}, 3000, dynamicValue, 200, 300);
Example-3: Passing the only first parameter to setTimeout()
In this case, the setTimeout function will take a default delay time of 0. It means the callback will be called immediately.
// Here an alert message will be displayed immediately
setTimeout(function(){
alert("Hello world!");
});
Working with asynchronous functions
The setTimeout()
is an asynchronous function, it means the timer function will not pause the execution of other functions in the function’s stack. In other words, you cannot use setTimeout()
to create a “pause” before the next function in the function stack fires.
For example-
setTimeout(function(){
console.log("this is the first message");
}, 5000);
setTimeout(function(){
console.log("this is the second message");
}, 3000);
setTimeout(function(){
console.log("this is the third message");
}, 1000);
//Output:
//this is the third message
//this is the second message
//this is the first message
Note: Please notice here, the first function does not create a 5-second “pause” before calling the second function. Similarly, other functions also will not pause the execution flow, which means all functions are calling immediately but the messages have been displayed after specified delays only.
Maximum delay value in setTimeout
Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 milliseconds (about 24.8 days), resulting in the timeout being executed immediately.
The setTimeout inside for loop
Let’s see how a setTimeout executes inside a JavaScript for loop. Look at the below piece of code:
// setTimeout function calling inside a for loop
for(var i = 0;i < 5; i++){
setTimeout(function(){
console.log("count ="+ i);
}, 1000);
}
//Output:
//count =5
//count =5
//count =5
//count =5
//count =5
What happened here? When we execute the above piece of code, we will see the last value of i being printed each time ie. 5.
Let’s understand the problem
The setTimeout function callback is not triggered until the for loop execution has been completed. When the for loop has finished executing the value of i is 5. Now when the setTimeout call begins to execute it uses the last set value of i which is 5. That’s why the setTimeout function printed 5 each time.
How to resolve this problem?
Solution#1: Using let keyword
When we use the ES6 let keyword inside the for loop, it creates a separate scope for each iteration making it possible to print the consecutive variable value. Now look at the modified code below:
// using let keyword
for(let i = 0;i < 5; i++){
setTimeout(function(){
console.log("count ="+ i);
}, 1000);
}
//Output:
//count =0
//count =1
//count =2
//count =3
//count =4
Solution#2: Using IIFE (Immediately Invoked Function Expression)
IIFE can be used to create a new scope for each setTimeout callback without polluting the global scope. Simply put all the setTimeout code inside an IIFE. Let’s see the sample code below:
// using IIFE
for(var i = 0; i < 5; i++){
(function(i){
setTimeout(function(){
console.log("count ="+i);
}, 1000);
})(i);
}
//Output:
//count =0
//count =1
//count =2
//count =3
//count =4
Solution#3: Using setTimeout in a separate method
One more solution is setting setTimeout in a separate method to create a new scope for each method call. Let’s see the code below:
// Using setTimeout in a separate method
function delayPrint(i){
setTimeout(function(){
console.log("count ="+i);
}, 1000);
}
for(var i = 0; i < 5; i++){
delayPrint(i);
}
//Output:
//count =0
//count =1
//count =2
//count =3
//count =4
Clearing the setTimeout()
The global clearTimeout()
method clears or cancels a timeout previously established by calling setTimeout()
. The setTimeout method returns a timeoutId (an integer value) which is used by the clearTimeout() method to clear the timeout.
For example:
var timeoutId=setTimeout(function(){
alert("Hello world!");
},5000);
// call this method before 5 second
clearTimeout(timeoutId);
Note: Passing an invalid timeoutId to clearTimeout()
silently does nothing, no exception is thrown.
Using the setTimeout() like setInterval() method
The setTimeout() method calls a function after a specified number of milliseconds only once whereas, The setInterval() method repeats a given function at every given time interval.
Now let’s see how we can use setTimeout like setInterval.
It is possible when we use setTimeout in a method and that method will be called recursively inside setTimeout function. Let’s see sample example below:
<div id="box1" style="height:200px;width:200px;background:orange;"></div>
<script>
var count=0;
var colors=['red','green','yellow','blue','orange'];
function setColor(){
setTimeout(function(){
var box1=document.getElementById('box1');
box1.style.background=colors[count++];
if(count==5){
count=0;
}
setColor();
},1000);
}
// first time only
setColor();
</script>
Conclusion
In this article, you have seen how to use the setTimeout method in Javascript. learn more about setTimeout.
Applications using setTimeout
You can see some applications developed using the setTimeout method below.
FAQ
Is setTimeout bad for performance?
No significant effect at all, setTimeout runs in an event loop, it doesn’t block or harm execution.
Does setTimeout stop execution?
No, setTimeout does not pause the execution of other code.
When should I use setTimeout?
Sometimes it is necessary to program a function call in a specific moment. The JavaScript setTimeout() function is ready to help you with this task-scheduling by postponing the execution of a function until the specified time.
Is there a sleep function in Javascript?
Unlike Java or Python, Javascript does not have a built-in sleep function. A simple way to create a delay in Javascript is to use the setTimeout method.