waitify
v2.0.1
Published
A flexible and feature-rich delay utility for JavaScript with pause/resume, progress tracking, retry, and more.
Downloads
58,468
Maintainers
Readme
Enhanced Delay (Waitify)
A flexible and feature-rich delay utility for JavaScript that goes beyond a simple timeout.
Features
- Basic delay - Simple promise-based delay
- Callback support - Execute a function after the delay
- Jitter - Add random variance to delay times
- Progress tracking - Monitor delay progress
- Pause/Resume - Pause and resume delays
- Timeout protection - Set maximum wait time
- Retry logic - Automatically retry with configurable backoff
- Cancellation - Cancel pending delays
Installation
npm install waitify
Usage
Basic Delay
const delay = require('waitify');
// Simple delay
const { promise } = delay(1000);
await promise; // Waits for 1 second
With Callback
// With callback
delay(1000, () => {
console.log('1 second has passed!');
});
// Or using object syntax
delay(1000, {
callback: () => console.log('1 second has passed!')
});
Progress Tracking
delay(5000, {
onProgress: (percentage) => {
console.log(`Progress: ${percentage}%`);
}
});
Jitter
Add random variance to avoid thundering herd problems in distributed systems:
// 10% jitter (900-1100ms)
delay(1000, {
jitter: 0.1
});
Pause and Resume
const delayObj = delay(10000);
// Later...
const remainingTime = delayObj.pause();
console.log(`Paused with ${remainingTime}ms remaining`);
// Resume when needed
delayObj.resume();
Retry Logic
delay(1000, {
callback: () => {
// This will retry if it throws an error
makeApiCall();
},
maxRetries: 3,
retryDelay: 500,
exponentialBackoff: true,
onRetry: (retryCount) => {
console.log(`Attempt ${retryCount} failed, retrying...`);
}
});
Timeout Protection
try {
await delay(5000, {
timeout: 2000
}).promise;
} catch (error) {
console.error('Delay timed out');
}
Cancellation
const { promise, cancel } = delay(10000);
// Later...
cancel();
API Reference
delay(ms, options)
Returns a DelayResult
object with the following properties:
promise
- Promise that resolves when the delay completescancel()
- Function to cancel the delaypause()
- Pause the delay and return remaining timeresume()
- Resume a paused delayretryCount
- Number of retry attempts (if retries enabled)elapsedTime
- Total elapsed time in millisecondsisRunning
- Whether the delay is currently running
Options
callback
- Function to call after delayjitter
- Random variance factor (0-1)maxRetries
- Maximum retry attemptsretryDelay
- Delay between retriesexponentialBackoff
- Whether to use exponential backoff for retriestimeout
- Maximum time to wait (0 = no timeout)onProgress
- Progress callback (receives percentage 0-100)onRetry
- Called when a retry occurs (receives retry count)
License
Unlicense: Free to do anything with it, IDGAF!