Javascript for loop delay

I want to delay the for loop a bit, but don’t know how to do it.

For instance. Say this "for loop" works from 0 to 8, and after each I should have a delay of 2 seconds.

for (var i=0; i<8; i++{ do something... wait for 2 sek. and go on with i=i++; } 
+6
source share
3 answers

You will have to go as follows:

 function jsHello(i) { if (i < 0) return; setTimeout(function () { alert("Hello " + i); jsHello(--i); }, 2000); } jsHello(5); 

or

 function jsHello(i) { alert("Hello " + i); if (--i > -1) { setTimeout(function () { jsHello(i); }, 2000); } } jsHello(5); 
+8
source

There is no wait command in Javascript. The way to get this behavior is using setTimeout :

 for (var i=0; i<8; i++){ do_something(i); } function do_something(j) { setTimeout(function() { tasks to do; }, 2000 * j); } 

Each time the do_something() function is called, it performs the "tasks to be completed" scheduled for 2000*i milliseconds.

+2
source

To solve this problem, you should use closure - immediately call a function that is called at each iteration using i as a parameter, and setTimeout inside this function. In this case, the parameter that you passed will be stored in scope and can be used in the timeout callback:

 for (var i=0; i<8; i++) (function(t) { window.setTimeout(function() { //do anything with t }, t*2000) }(i)) 
+2
source

Source: https://habr.com/ru/post/1208882/


All Articles