sleep()
Prompt
Write a sleep function in JavaScript that pauses code execution for a given number of milliseconds. The function should return a Promise that resolves after the specified delay.
JavaScript is a single-threaded, non-blocking language, which means it doesn't have a built-in sleep function like some other languages do. However, there are ways to emulate the same behavior.
Playground
The function needs to return a Promise. Think about how
you create a new Promise and what controls when it
resolves.
JavaScript has a built-in function that executes a callback after a specified delay. How can you connect that to a Promise's resolve?
Solution
Explanation
What does sleep do?
In many programming languages like Python or Java, there's a built-in way to pause your program for a set amount of time. JavaScript doesn't have this out of the box, but we can build it ourselves using two tools we already have: Promises and setTimeout.
The idea is simple: create a Promise that doesn't resolve right away. Instead, it waits for setTimeout to fire after the given number of milliseconds, and then it resolves.
How the solution works
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}Let's break this single line down:
new Promise((resolve) => ...)-- We create a new Promise. The Promise gives us aresolvefunction that we can call whenever we're "done."setTimeout(resolve, ms)-- We tell JavaScript: "Aftermsmilliseconds, callresolve." That's it. We're just passingresolvedirectly as the callback tosetTimeout.- When
resolveis called, the Promise transitions from pending to fulfilled, and any code waiting on it (via.then()orawait) continues executing.
Walking through the example
console.log('Starting...'); // Runs immediately
await sleep(2000); // Pauses here for 2 seconds
console.log('2 seconds later'); // Runs after the delayWhen await sleep(2000) is hit, JavaScript creates a Promise with a 2-second timer. Execution pauses at that line (without blocking the thread). After 2 seconds, setTimeout fires, the Promise resolves, and the next line runs.
Two ways to use it
With .then():
sleep(1000).then(() => {
console.log('Done!');
});With async/await:
async function run() {
await sleep(1000);
console.log('Done!');
}Both achieve the same result. The async/await version reads more like synchronous code, which is why most developers prefer it.
Common Mistake
If you use await outside of an async function, you'll
get a syntax error. Remember: await can only be used
inside functions declared with the async keyword.