is there a way to do a setTimout for each iteration of a loop?
I basically want each iteration at 500
setTimeout(function(), 500);
}
If so, how would it look?
for (var i = 0; i < 10; i++){
}
is there a way to do a setTimout for each iteration of a loop?
I basically want each iteration at 500
setTimeout(function(), 500);
}
If so, how would it look?
for (var i = 0; i < 10; i++){
}
So you have a piece of code that you want to execute N number of times, waiting 500ms between each execution?
You could use setInterval (https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval) instead of setTimeout, and then within the code you're executing on the interval, include a counter and a condition to remove the interval (Stop setInterval call in JavaScript) after the correct number of executions.
You can't do this type of stuff in a for
loop. But you can emulate it:
var latency = 500,
iteration = 0,
numIterations = 10;
var loop = function() {
// Do your stuff, like:
console.log( iteration );
/*
// break; simulation - return early if some condition was achieved:
if ( iteration == 8 ) {
return;
}
*/
// Loop handling, you'll need those lines, don't remove.
iteration += 1;
if ( iteration < numIterations ) {
setTimeout( loop, latency );
}
}
loop(); // invoke first cycle