I want that my for loop should not be executed at once, but wait for timeout after each iteration. For eg :
for(var i=0; i<10; i++) { console.log(i); //wait for 1000 }
I found many solutions on stack-overflow like this one :
for (var i=0;i<=10;i++) { (function(ind) { setTimeout(function(){console.log(ind);}, 3000); })(i); }
But in all the implementations, the loop waits for 3000 milli-seconds initially and then executes the whole for
loop at once. Is there a way that each iteration is called after waiting for 1000 milli-seconds.
The setTimeout function callback isn't triggered until the for loop execution has 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. Hence 5 is printed in all the setTimeout callbacks.
setTimeout function in JavaScript usually takes a callback function as an argument. A callback function is a function that is executed after another function finishes running. In this case, it will run after for loop finishes.
Using the ES6 let keyword inside the for loop, creates a separate scope for each iteration making it possible to print the consecutive variable value. IIFE can be used to create a new scope for each setTimeout callback without polluting the global scope. Simply wrap up the setTimeout code inside an IIFE.
The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);
You can work that out with simple math :
for (var i=0;i<=10;i++) { (function(ind) { setTimeout(function(){console.log(ind);}, 1000 + (3000 * ind)); })(i); }
1000ms : 0
4000ms : 1
7000ms : 2
10000ms : 3
13000ms : 4
...
It seem that your request is a bit blurry. if you want to do something after the last timeout, you can set a limit and compare the current index :
var limit = 10 for (var i=0;i<=limit;i++) { (function(ind) { setTimeout(function(){ console.log(ind); if(ind === limit){ console.log('It was the last one'); } }, 1000 + (3000 * ind)); })(i); }
Fiddle : http://jsfiddle.net/Tn4A7/
and it is to simply do
for (var i=0;i<=10;i++) { (function(ind) { setTimeout(function(){console.log(ind);}, 1000 * ind); })(i); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With