Skip to main content

sleep()

sleep(ms): Promise<void>

Pauses execution for a specified duration.


Parameters​

ms: number​

Duration to sleep in milliseconds (must be non-negative).


Returns: Promise<void>​

Promise that resolves after the specified duration.


Throws​

RangeError If ms is negative.


Since​

2.0.0


Also known as​

delay (es-toolkit) · sleep (Radashi, Effect, Modern Dash, Antfu) · ❌ (Lodash, Remeda, Ramda)


Example​

await sleep(1000);
console.log('1 second later');

// Sequential delays
for (const item of items) {
await process(item);
await sleep(100);
}

How it works?​

Pauses execution for a specified duration. Returns a Promise that resolves after the delay.

Usage​

Sequential Delays​

Rate limiting between operations.


Use Cases​

Delay async execution πŸ“Œβ€‹

Pause async execution for a specific duration. Essential for throttling, polling intervals, or simulating latency in tests.

await sleep(1000); // Wait 1 second
await fetchData();

Respect API rate limits​

Introduce delays between batch operations to avoid hitting rate limits.

for (const item of batch) {
await sendRequest(item);
await sleep(100); // 100ms between requests
}

Simulate network latency​

Add artificial delays in development/testing environments.

if (isDev) {
await sleep(500); // Simulate slow network
}
return mockData;

Animate sequential UI elements​

Stagger entrance animations for list items or cards. Perfect for loading sequences and reveal animations.

const staggerReveal = async (elements: HTMLElement[]) => {
for (const el of elements) {
el.classList.add("visible");
await sleep(80); // 80ms stagger between each item
}
};

staggerReveal([...document.querySelectorAll<HTMLElement>(".card")]);

Implement a countdown timer​

Display a countdown before starting an action or game round. Essential for game lobbies, quiz timers, and timed events.

const countdown = async (seconds: number, onTick: (remaining: number) => void) => {
for (let i = seconds; i > 0; i--) {
onTick(i);
await sleep(1000);
}
onTick(0);
};

await countdown(3, (n) => {
display.textContent = n === 0 ? "Go!" : String(n);
});
startGame();

Wait for CSS transition to complete​

Pause execution until a CSS transition finishes before proceeding. Essential for sequencing JS logic after CSS animations.

const collapsePanel = async (panel: HTMLElement) => {
panel.classList.add("collapsing");
await sleep(300); // Match CSS transition-duration
panel.classList.remove("collapsing");
panel.classList.add("collapsed");
panel.style.display = "none";
};

Delay tooltip appearance​

Show a tooltip only after the user hovers for a minimum duration. Prevents tooltips from flashing during quick mouse movements.

let isStillHovering = false;

element.addEventListener("mouseenter", async () => {
isStillHovering = true;
await sleep(400); // 400ms hover delay
if (isStillHovering) {
showTooltip(element);
}
});

element.addEventListener("mouseleave", () => {
isStillHovering = false;
hideTooltip();
});