set timeout for loop javascript code example
Example 1: settimeout inside loop
//you can leave the sleep constant
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
const doSomething = async () => {
for (/*for loop statements here*/) {
//code before sleep goes here, just change the time below in milliseconds
await sleep(1000)
//code after sleep goes here
}
}
doSomething();
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 a for loop javascript
// make sure to use "let" and not "var" if you want to capture
// the value of the external variable in a closure
for (let i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 0);
}