-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimers.ts
More file actions
42 lines (39 loc) · 1.47 KB
/
Copy pathtimers.ts
File metadata and controls
42 lines (39 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @file Browser-compatible promise-based timer helpers. Uses
* `globalThis.setTimeout` / `globalThis.queueMicrotask` directly so every
* export works in browsers, Node.js, Deno, Bun, and Web Workers without
* importing `node:timers/promises`. In Node.js test environments with
* `vi.useFakeTimers()` / `clock.install()`, vitest/sinon replace
* `globalThis.setTimeout` before this module loads, so fake timers advance
* `sleep()` correctly — no special wiring needed. For Node-only
* abort-signal-aware delays see `promises/_internal.ts`.
*/
import { PromiseCtor } from '../primordials/promise'
/**
* Pause for `ms` milliseconds. Resolves with `undefined` when the timer fires.
* Negative values are clamped to 0.
*
* @example
* await sleep(100)
*/
export function sleep(ms: number): Promise<void> {
return new PromiseCtor<void>(resolve => {
setTimeout(resolve, ms > 0 ? ms : 0)
})
}
/**
* Yield to the event loop once. Resolves after the current call stack and any
* already-queued microtasks have completed — equivalent to `setTimeout(fn, 0)`
* as described in
* https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#late_timeouts.
* Useful for flushing microtask queues in tests or giving the browser a repaint
* opportunity between heavy operations.
*
* @example
* await yieldToEventLoop()
*/
export function yieldToEventLoop(): Promise<void> {
return new PromiseCtor<void>(resolve => {
setTimeout(resolve, 0)
})
}