I understand that there is not a native sleep
or wait
method in JavaScript. However, I am aware of the setTimeout
method, and I am trying to use it to delay execution within a loop.
I am trying to delay the printing of the iteration (i.e. 0, 1, 2) in three second intervals.
function load () {
for (var i = 0; i < 3; i++) {
console.log(i);
setTimeout(function() {console.log('sleeping three seconds')}, 3000);
}
}
This outputs:
0
1
2
and after three seconds
(3) sleeping three seconds
However, I'm trying to have a three second pause between iteration, so that I have execution as:
0
sleeping three seconds
1
sleeping three seconds
2
sleeping three seconds