To execute JavaScript setTimeout in loop do print each time on setTimeout callback execution. The setTimeout function callback isn’t triggered until the for loop execution has been completed.
for(var i = 0;i < 5; i++){
setTimeout(function(){
console.log('count ', i);
}, 3000);
}
hen 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. Hence 5 is printed in all the setTimeout callbacks.
JavaScript setTimeout loop
For simple example the loop waits for 3000 milli-seconds initially and then executes the whole for
loop at once.
<!DOCTYPE html>
<html>
<body>
<script>
var array = [1, 2, 3, 4, 5];
for(let i = 0; i < array.length; i++) {
setTimeout(() => {
console.log(array[i])
}, 1000);
}
</script>
</body>
</html>
Another example is where each iteration is called after waiting for 1000 milliseconds.
<script>
var array = [1, 2, 3, 4, 5];
for (var i=0; i<array.length; i++) {
(function(ind) {
setTimeout(function(){console.log(array[ind]);}, 1000 * ind);
})(i);
}
</script>
Output:
If you want to create a loop in JavaScript using setTimeout
, you can achieve this by using a recursive function. Here’s an example:
function myLoop(i) {
setTimeout(function () {
console.log("Iteration: " + i);
// Your code here
i++;
if (i < 10) {
myLoop(i); // Call the function again for the next iteration
}
}, 1000); // Adjust the timeout duration (in milliseconds) as needed
}
// Start the loop with the initial value
myLoop(0);
1. setTimeout Inside For Loop Using IIFE (Immediately Invoked Function Expression)
Use IIFE to create a new scope for each setTimeout callback without polluting the global scope. Simply wrap up the setTimeout code inside an IIFE. Here is how it looks:
// setTimeout inside for loop with IIFE Wrapper
for(var i = 0; i < 5; i++){
(function(i){
setTimeout(function(){
console.log('value is ', i);
}, 3000);
})(i);
}
2. setTimeout Inside For Loop Using Let Keyword
The let keyword creates a separate scope for each iteration making it possible to print the consecutive variable value. Here is how the code looks:
// setTimeout inside For loop Using let keyword
for(var i = 0;i < 5; i++){
let k = i;
setTimeout(function(){
console.log('count ', k);
}, 3000 * (k + 1));
}
Execute the above piece of code and you will be able to view the numbers from 0 to 4 printed in the browser console.
Do comment if you have any doubts or suggestions on this JS set Timeout topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version