In JavaScript, there’s no built-in sleep()
function like in Python or C, but you can achieve similar behavior using promises and async/await
syntax. Here are the most common ways to implement a delay:
1. Using setTimeout
with Promises (Modern Approach)
Create a reusable sleep()
function that returns a promise resolved after a delay:
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Usage in an async function:
async function demo() {
console.log("Start");
await sleep(2000); // Pauses for 2 seconds
console.log("End");
}
demo();
How it works:
sleep(ms)
returns a promise that resolves afterms
milliseconds.await
pauses execution of theasync
function until the promise resolves.
2. Classic setTimeout
(Without Promises)
Use a callback-based approach for simple delays (legacy code):
console.log("Start");
setTimeout(() => {
console.log("End");
}, 2000); // Executes after 2 seconds
Limitations:
- Callbacks can lead to “callback hell” if chaining delays.
- Not as clean as
async/await
for sequential logic.
3. Synchronous Blocking (Avoid This!)
Never use while
loops or Date
checks to block execution:
// ❌ This freezes the browser/Node.js!
function syncSleep(ms) {
const start = Date.now();
while (Date.now() - start < ms) {}
}
console.log("Start");
syncSleep(2000); // Blocks the entire thread
console.log("End");
Why avoid this?
- Blocks the entire JavaScript runtime (UI freezes in browsers, server unresponsive in Node.js).
- Defeats the purpose of JavaScript’s asynchronous nature.
Key Notes
- Async/Await Required: The
await
keyword only works insideasync
functions. - Non-Blocking: The
sleep()
function using promises does not block other code execution. - Browser/Node.js Support: Works in all modern environments.
Advanced Use Cases
Chaining Delays:
async function delayedGreeting() {
await sleep(1000);
console.log("Hello");
await sleep(1000);
console.log("World");
}
delayedGreeting();
Loop with Delay:
async function countdown() {
for (let i = 5; i > 0; i--) {
console.log(i);
await sleep(1000);
}
}
countdown();
Node.js Timers/Promises (v15+):
import { setTimeout } from 'timers/promises';
// or: const { setTimeout } = require('timers/promises');
async function nodeDemo() {
await setTimeout(2000);
console.log("Done");
}
Summary Table
Method | Example | Use Case |
---|---|---|
sleep() + async/await | await sleep(2000); | Clean, modern code |
setTimeout callback | setTimeout(() => {}, 2000); | Simple delays (legacy code) |
timers/promises (Node) | await setTimeout(2000); | Node.js-specific syntax |
Why Promises/Async?
- Avoid callback hell.
- Write sequential-looking code for asynchronous operations.
- Integrates with other promise-based APIs (e.g.,
fetch
).
Use the promise-based sleep()
for most scenarios!