-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeout Cancellation
More file actions
33 lines (32 loc) · 828 Bytes
/
Timeout Cancellation
File metadata and controls
33 lines (32 loc) · 828 Bytes
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
function cancellable(fn: Function, args: any[], t: number): Function {
const cancelFn: any = () => clearTimeout(timer);
const timer: ReturnType<typeof setTimeout> = setTimeout(() => {
fn(...args);
}, t);
return cancelFn;
};
/**
* const result = []
*
* const fn = (x) => x * 5
* const args = [2], t = 20, cancelT = 50
*
* const start = performance.now()
*
* const log = (...argsArr) => {
* const diff = Math.floor(performance.now() - start);
* result.push({"time": diff, "returned": fn(...argsArr)})
* }
*
* const cancel = cancellable(log, args, t);
*
* const maxT = Math.max(t, cancelT)
*
* setTimeout(() => {
* cancel()
* }, cancelT)
*
* setTimeout(() => {
* console.log(result) // [{"time":20,"returned":10}]
* }, maxT + 15)
*/