What is the JavaScript alternative to the sleep function

In JavaScript, the sleep() function is not a built-in function. However, you can achieve a similar effect by using the setTimeout(), setInterval() or Date.now() functions.

Using setTimeout()

setTimeout() is a method that takes two arguments: a function to be executed and a delay time in milliseconds. The function will execute after the specified delay time has passed.

Following is an example of how to use setTimeout() to create a sleep function in JavaScript:

function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }

In the example above, sleep() takes an argument ms that specifies the time to wait in milliseconds. The function returns a Promise that resolves after the specified time has elapsed.

You can then use this sleep() function in your code like this:

async function mySleepFunction() { console.log('start'); await sleep(2000); console.log('end'); }

In the example above, mySleepFunction() logs "start" to the console, waits for 2 seconds using the sleep() function, and then logs "end" to the console.

FullSource | JavaScript:
function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function mySleepFunction() { console.log('start'); await sleep(2000); console.log('end'); } mySleepFunction();

Note that the sleep() function returns a Promise, so you need to use await when calling it. This means that you need to define your function as async as well.

Using setInterval()


How to Javascript sleep

Alternatively, you can use the setInterval() function to create a sleep function in JavaScript. The setInterval() function allows you to repeatedly execute a function at a specified interval.

Folllowing an example of how to use setInterval() to create a sleep function in JavaScript:

function sleep(ms) { return new Promise(resolve => { const intervalId = setInterval(() => { clearInterval(intervalId); resolve(); }, ms); }); }

In the example above, sleep() takes an argument ms that specifies the time to wait in milliseconds. The function returns a Promise that resolves after the specified time has elapsed. The setInterval() function is used to repeatedly execute a function that clears the interval and resolves the Promise after the specified delay.

You can then use this sleep() function in your code like this:

async function mySleepFunction() { console.log('start'); await sleep(2000); console.log('end'); }

In the example above, mySleepFunction() logs "start" to the console, waits for 2 seconds using the sleep() function, and then logs "end" to the console.

FullSource | JavaScript:
function sleep(ms) { return new Promise(resolve => { const intervalId = setInterval(() => { clearInterval(intervalId); resolve(); }, ms); }); } async function mySleepFunction() { console.log('start'); await sleep(2000); console.log('end'); } mySleepFunction();

Note that the sleep() function returns a Promise, so you need to use await when calling it. This means that you need to define your function as async as well.

Using Date.now()

Also, you can use the Date.now() function to create a sleep function in JavaScript. The Date.now() function allows you to repeatedly execute a function at a specified interval.

function sleep(ms) { const start = Date.now(); while (Date.now() - start < ms){} }

Inside the sleep function, it gets the current timestamp using Date.now() and stores it in the start variable. It then enters a while loop which continuously checks if the difference between the current timestamp and the start timestamp is less than the ms value passed in as an argument to the function.

async function mySleepFunction() { console.log('start'); await sleep(2000); console.log('end'); }

While the difference is less than the specified sleep time, the loop keeps running and blocking the execution of the code. Once the difference exceeds the specified time, the loop exits, and the function returns.

FullSource | JavaScript:
function sleep(ms) { const start = Date.now(); while (Date.now() - start < ms){} } async function mySleepFunction() { console.log('start'); await sleep(2000); console.log('end'); } mySleepFunction();

While this approach may achieve the goal of blocking code execution for a specific duration, it has some downsides. The while loop is a busy-wait loop, which means that it consumes CPU resources unnecessarily while waiting. This can make your application less responsive and cause performance issues.

Conclusion

It is generally recommended to use setTimeout() or setInterval() to create a sleep function in JavaScript, as these methods use less CPU resources and do not block the event loop.