Aller au contenu principal

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;