sleep-await
v1.0.3
Published
A comprehensive async timing utility featuring abortable sleep, timeout, retry, and polling (waitUntil). TypeScript native.
Maintainers
Readme
sleep-await ⏳
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).
Why sleep-await?
| Feature | sleep-await | Standard setTimeout | delay package |
| :--- | :---: | :---: | :---: |
| TypeScript Native | ✅ | ✅ | ✅ |
| CommonJS & ESM | ✅ | ⚠️ | ❌ (ESM only) |
| AbortSignal (Cancel) | ✅ | ❌ | ✅ |
| Timeout Wrapper | ✅ | ❌ | ❌ |
| Polling (WaitUntil) | ✅ | ❌ | ❌ |
| Retry Utility | ✅ | ❌ | ❌ |
Installation
npm install sleep-await
# or
yarn add sleep-await
# or
pnpm add sleep-awaitUsage
1. Sleep (Advanced)
Standard 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
}2. Timeout
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!');
}3. WaitUntil (Polling)
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
});4. Retry
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
});Legacy Support (v1.0.x Users)
The original sleepAwait function is preserved but deprecated.
import { sleepAwait } from 'sleep-await';
await sleepAwait(1000); // Still works exactly as before!License
ISC
