Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 48b3a1a

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

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎Timeout Cancellation‎

Lines changed: 33 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /