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.
functionsleep(ms) {
returnnewPromise(resolveFunc =>setTimeout(resolveFunc, ms));
}
asyncfunctionsleepingFunc() {
for (let i = 0; i < 5; ++i) {
console.log(i + " - from sleep");
awaitsleep(1000);
}
}
functionsynchronousFunc() {
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.
constwork = (i)=>{
console.log('doing work here ', i);
}
let counter = 0const timer = setInterval(()=>{
if (timer && ++counter >= 10) {
clearInterval(timer)
}
work(counter);
}, 1000)
Post a Comment for "Add Timeout / Sleep Function Inside Javascript Loop"