Skip to content

Commit 48b3a1a

Browse files
authored
Create Timeout Cancellation
1 parent 2141b8a commit 48b3a1a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Diff for: Timeout Cancellation

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
function cancellable(fn: Function, args: any[], t: number): Function {
2+
const cancelFn: any = () => clearTimeout(timer);
3+
const timer: ReturnType<typeof setTimeout> = setTimeout(() => {
4+
fn(...args);
5+
}, t);
6+
return cancelFn;
7+
};
8+
9+
/**
10+
* const result = []
11+
*
12+
* const fn = (x) => x * 5
13+
* const args = [2], t = 20, cancelT = 50
14+
*
15+
* const start = performance.now()
16+
*
17+
* const log = (...argsArr) => {
18+
* const diff = Math.floor(performance.now() - start);
19+
* result.push({"time": diff, "returned": fn(...argsArr)})
20+
* }
21+
*
22+
* const cancel = cancellable(log, args, t);
23+
*
24+
* const maxT = Math.max(t, cancelT)
25+
*
26+
* setTimeout(() => {
27+
* cancel()
28+
* }, cancelT)
29+
*
30+
* setTimeout(() => {
31+
* console.log(result) // [{"time":20,"returned":10}]
32+
* }, maxT + 15)
33+
*/

0 commit comments

Comments
 (0)