delay a for loop with javascript
Javascript doesn't have a wait command. 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);
}
Every time the function do_something()
is called, it executes "tasks to do" scheduled by 2000*i
milliseconds.
You'll have to go that way:
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);