Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript : For loop with timeout

Tags:

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.

like image 704
Parag Gangil Avatar asked Jun 18 '14 19:06

Parag Gangil


People also ask

Can we use setTimeout in for loop?

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.

How does setTimeout work in loop?

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.

How will setTimeout respond inside for loop and using IIFE and let inside it?

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.

How do I create a timeout in JavaScript?

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);


1 Answers

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
...


Following the comments

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/


I think I know what you want...

and it is to simply do

for (var i=0;i<=10;i++) {    (function(ind) {        setTimeout(function(){console.log(ind);}, 1000 * ind);    })(i); } 
like image 127
Karl-André Gagnon Avatar answered Sep 21 '22 16:09

Karl-André Gagnon