The Modern, Abortable, and Precise Async Timing Utilities for Node.js & Browser.
sleep-await is a lightweight, zero-dependency collection of async timing utilities. It goes beyond simple pausing, offering robust tools for timeouts, polling, retries, and cancellation (AbortSignal).
| Feature | sleep-await |
Standard setTimeout |
delay package |
|---|---|---|---|
| TypeScript Native | ✅ | ✅ | ✅ |
| CommonJS & ESM | ✅ | ❌ (ESM only) | |
| AbortSignal (Cancel) | ✅ | ❌ | ✅ |
| Timeout Wrapper | ✅ | ❌ | ❌ |
| Polling (WaitUntil) | ✅ | ❌ | ❌ |
| Retry Utility | ✅ | ❌ | ❌ |
npm install sleep-await
# or
yarn add sleep-await
# or
pnpm add sleep-awaitStandard pause, but with AbortSignal support.
import { sleep } from 'sleep-await';
async function performTask() {
console.log('Start');
await sleep(1000); // Wait for 1 second
console.log('End');
}
// With AbortSignal
const controller = new AbortController();
setTimeout(() => controller.abort(), 500); // Abort after 500ms
try {
await sleep(2000, { signal: controller.signal });
} catch (error) {
console.log('Sleep was aborted!'); // This will run
}Wrap any promise with a strict timeout.
import { timeout } from 'sleep-await';
try {
const data = await timeout(fetch('https://slow-api.com'), 1000);
} catch (error) {
console.error('Request timed out!');
}Wait for a condition to become true. Perfect for integration tests or waiting for resources.
import { waitUntil } from 'sleep-await';
await waitUntil(() => db.isConnected(), {
interval: 100, // Check every 100ms
timeout: 5000, // Give up after 5 seconds
});Retry a failing async operation with exponential backoff.
import { retry } from 'sleep-await';
await retry(() => api.fetchData(), {
retries: 3,
delay: 200, // Start with 200ms delay
backoffFactor: 2 // 200ms -> 400ms -> 800ms
});The original sleepAwait function is preserved but deprecated.
import { sleepAwait } from 'sleep-await';
await sleepAwait(1000); // Still works exactly as before!ISC