Skip to content

pic123123/sleep-await

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

sleep-await ⏳

The Modern, Abortable, and Precise Async Timing Utilities for Node.js & Browser.

npm version minzipped size License: ISC

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-await

Usage

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

About

It waits for the number of milliseconds of the argument you put into the function before executing it. This function must use async await. Execution is paused through the awiat keyword, and execution resumes when the promise is processed.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors