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;