Explain Codes LogoExplain Codes Logo

What is the JavaScript version of sleep()?

javascript
async-await
event-loop
non-blocking
Alex KataevbyAlex Kataev·Mar 11, 2025
TLDR

For a quick solution, async/await and setTimeout are used together in a sleep function:

// Creating a sleep function const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); // Let's see this function in action async function action() { console.log('Before sleep'); // "I'm not sleep! You're asleep!" await sleep(2000); // Who doesn't like a quick 2-second power nap? console.log('After sleep'); // "I was sleeping? No way!" } action();

Quick note here: The function sleep returns a Promise that resolves after the specified ms milliseconds. To pause your async function, you just use await with the sleep function.

Don't block the event loop

Back in the day, JavaScript "sleep" was often emulated using blocking loops or the Atomics.wait method. These are no longer recommended as they can block the main thread, causing performance woes or even unresponsive UI. The present-day approach leans on asynchronous patterns with setTimeout, letting us have non-blocking delays.

Old code? No problem!

If you're working with older code or cross-browser compatibility is a concern, no worries! Transpile your modern async/await syntax for older environments using Babel and the transform-async-to-generator plugin. This ensures that your sleep function works pretty darn well across a wide range of JavaScript environments.

Don't forget to clean up

Proper management of timeouts and intervals using clearTimeout and clearInterval can prevent potential memory leaks. This is especially important when your timeout or interval is no longer needed, or in situations like unmounting components in React.

Async/await to the rescue!

async/await is a key feature of ES2017 (ECMAScript 8). It provides syntactic sugar for working with promises, making asynchronous code look and behave a bit more like synchronous code. This is basically the "cherry-on-top" to the vanilla JavaScript practice of setTimeout for emulating sleep.

Beware the cost

While it's handy to use artificial sleep in some scenarios, you should consider the other side of it. Delays may hamper the user interaction and debugging process. It's always better to approach real event-driven solutions over contrived timeouts.

The Promise of JavaScript's event loop

The event loop and the role of Promise are the heart of understanding JavaScript’s non-blocking model. The event loop allows JavaScript to perform asynchronous actions in a single thread — making JavaScript able to "multitask" without getting tangled up in its shoelaces.

Await the results

Remember, although async/await is becoming a standard, the await keyword can only be used inside async functions or at the top-level code in the latest environments, like Node.js modules or scripts in the latest browsers.