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();
});