JavaScript - sleep function
In this short article, we're going to have a look at how in JavaScript create sleep(ms)
function.
Quick solution:
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// await sleep(1000); // <------ use it inside async function
Node:
async
/await
operators were introduced in ES8 (ES2017) - use Babel or TypeScript to provide this functionality in older web browsers.
Explanation
sleep()
function is not available in JavaScript, but it is possible to emulate sleeping with acync
functions. The main idea is to postpone resolve()
function call with setTimeout()
function wrapped in Promise
object. Later that created logic can be placed inside own sleep()
function and called with await
keyword inside async
method only - it is the main disadvantage/advantage of the approach. The async sleep()
function doesn't freeze the web browser as the infinity loop does that is the advantage.
A more complicated runnable example code is below:
// ONLINE-RUNNER:browser;
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Usage example:
const action = async () => {
console.log('[START]');
for (let i = 0; i < 5; ++i) {
await sleep(1000); // sleeps 1s each iteration
console.log(i);
}
console.log('[STOP]');
};
action();