Add Timeout / Sleep Function Inside Javascript Loop
Solution 1:
You can make use of ES6's async/await
-feature!
To use await
, it needs to be in a function/expression body declared async
.
Basically, this will make your function be asynchronous, and make it wait for a Promise
to be fulfilled. We make that Promise be fulfilled after a set delay using setTimeout()
.
Note that "after a set delay" does not mean "exactly after", it basically means "as early as possible after".
By doing this, the asynchronous function waits for the promise to be fulfilled, freeing up the callstack in the meantime so that other code can be executed.
The order of execution of this example is (simplified) as follows:
sleepingFunc()
is placed on callstack- In iteration:
await
for Promise to be fulfilled, suspending this call 🡒 freeing up callstack
- In iteration:
- Place new calls on callstack
- Eventually, Promise is fulfilled, ending
await
🡒 place suspended call back on callstack - Repeat until
sleepingFunc()
finished
As you can see in step 3, if other calls take up more time than the delay, the suspended call will have to wait that extra time longer.
function sleep(ms) {
return new Promise(resolveFunc => setTimeout(resolveFunc, ms));
}
async function sleepingFunc() {
for (let i = 0; i < 5; ++i) {
console.log(i + " - from sleep");
await sleep(1000);
}
}
function synchronousFunc() {
for (let i = 0; i < 5; ++i) {
console.log(i + " - from sync");
}
}
sleepingFunc();
synchronousFunc();
Solution 2:
This runs snippet runs one task every 1 second until the condition is satisfied, and then clears the timer.
const work = (i)=>{
console.log('doing work here ', i);
}
let counter = 0
const timer = setInterval(()=>{
if (timer && ++counter >= 10) {
clearInterval(timer)
}
work(counter);
}, 1000)
Post a Comment for "Add Timeout / Sleep Function Inside Javascript Loop"