# time — Delays and Timers > `import { delay, Timer } from 'puffy-core/time'` > CJS: `const { time: { delay, Timer } } = require('puffy-core')` --- ## delay Creates a cancellable async delay (sleep). ### Signature ``` delay(timeout?: number|[number, number], response?: any) → Promise & { cancel: Function } ``` Parameters: - `timeout`: Milliseconds to wait. Default: 100. Pass `[min, max]` array for a random delay within range. - `response`: Optional value to resolve with after the delay completes. Returns: A Promise that resolves after the timeout. The promise has an additional `.cancel()` method to abort early. ### Example 1 — Basic delay ```js await delay(2000) // Wait 2 seconds ``` ### Example 2 — Random delay ```js await delay([1000, 5000]) // Wait random 1-5 seconds ``` ### Example 3 — Delay with return value ```js const result = await delay(1000, { hello:'world' }) // result = { hello: 'world' } — returned after 1 second ``` ### Example 4 — Cancellation ```js const race1 = delay(5000, 'slow') const race2 = delay(3000, 'fast') const winner = await Promise.race([race1, race2]) // winner = 'fast' // Cancel the loser to prevent it from keeping the event loop alive if (winner === 'fast') race1.cancel() else race2.cancel() ``` GOTCHA: Always cancel delays you no longer need. Open delays keep the Node.js event loop alive, which matters in serverless environments (Lambda, Cloud Functions) where you're billed for execution time. --- ## Timer Measures elapsed time. ### Constructor ``` new Timer() → Timer ``` Creates a timer that starts immediately. ### Methods ``` timer.time(unit?: string, restart?: boolean) → number timer.start() → void timer.reStart() → void // alias for start() ``` Parameters for `time()`: - `unit`: Time unit for the result. Default: `'millisecond'` - `restart`: If `true`, resets the timer after reading ### Supported units | Unit strings | Description | |---|---| | `'ms'`, `'millisecond'` | Milliseconds | | `'s'`, `'sec'`, `'second'` | Seconds (2 decimal places) | | `'m'`, `'min'`, `'minute'` | Minutes (2 decimal places) | | `'h'`, `'hour'`, `'hrs'` | Hours (2 decimal places) | ### Example ```js const timer = new Timer() // ... do some work ... await delay(1500) console.log(timer.time('ms')) // ~1500 console.log(timer.time('second')) // ~1.50 console.log(timer.time('minute')) // ~0.03 // Read and restart in one call const elapsed = timer.time('second', true) // returns elapsed, then resets // ... do more work ... await delay(500) console.log(timer.time('ms')) // ~500 (timer was restarted) // Manual restart timer.reStart() ```