generated from davidbonnet/foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout.ts
41 lines (38 loc) 路 1.1 KB
/
timeout.ts
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
import { getGlobal } from "../dependencies.js";
import type { Unregister } from "../types";
const {
setTimeout,
clearTimeout,
requestAnimationFrame,
cancelAnimationFrame,
} = getGlobal();
const MAX_TIMEOUT = 2147483647;
/**
* Calls `callback` after at least `duration` milliseconds. Returns a function that cancels the future call of `callback`, if not already called.
*
* @param duration Timeout duration in milliseconds.
* @param callback Called after the duration elapsed.
* @returns Function that cancels the call of `callback`.
*/
export function timeout(duration: number, callback: () => void): Unregister {
if (!duration && requestAnimationFrame && cancelAnimationFrame) {
const timer = requestAnimationFrame(callback);
return () => {
cancelAnimationFrame(timer);
};
}
let timer: ReturnType<typeof setTimeout> | undefined = setTimeout(
() => {
timer = undefined;
callback();
},
duration > MAX_TIMEOUT ? MAX_TIMEOUT : duration,
);
return () => {
if (timer === undefined) {
return;
}
clearTimeout(timer);
timer = undefined;
};
}