javascript settimeout for loop delay code example
Example 1: how to delay iterations in javascript
var i = 1; // set your counter to 1
function myLoop() { // create a loop function
setTimeout(function() { // call a 3s setTimeout when the loop is called
console.log('hello'); // your code here
i++; // increment the counter
if (i < 10) { // if the counter < 10, call the loop function
myLoop(); // .. again which will trigger another
} // .. setTimeout()
}, 3000)
}
myLoop(); // start the loop
Example 2: javascript settimeout loop
function timeout() {
setTimeout(function () {
// Do Something Here
// Then recall the parent function to
// create a recursive loop.
timeout();
}, 1000);
}
Example 3: settimeout in loop javascript
var array = [1, 2, 3, 4, 5]for(var i = 0; i < array.length; i++) { setTimeout(() => { console.log(array[i]) }, 1000);} // i = 5