Skip to content

Commit fc06487

Browse files
timeout cancellation javascript program
1 parent 63f022c commit fc06487

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

TimeoutCancellation.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Given a function fn, an array of arguments args, and a timeout t in milliseconds,
2+
// return a cancel function cancelFn.
3+
4+
// After a delay of t, fn should be called with args passed as parameters unless
5+
// cancelFn was invoked before the delay of t milliseconds elapses, specifically
6+
// at cancelT ms. In that case, fn should never be called.
7+
8+
/**
9+
* @param {Function} fn
10+
* @param {Array} args
11+
* @param {number} t
12+
* @return {Function}
13+
*/
14+
var cancellable = function(fn, args, t) {
15+
const timeoutId = setTimeout(function() {
16+
fn.apply(null, args);
17+
}, t);
18+
19+
const cancelFn = function() {
20+
clearTimeout(timeoutId);
21+
};
22+
23+
return cancelFn;
24+
};
25+
26+
/**
27+
* const result = []
28+
*
29+
* const fn = (x) => x * 5
30+
* const args = [2], t = 20, cancelT = 50
31+
*
32+
* const start = performance.now()
33+
*
34+
* const log = (...argsArr) => {
35+
* const diff = Math.floor(performance.now() - start);
36+
* result.push({"time": diff, "returned": fn(...argsArr))
37+
* }
38+
*
39+
* const cancel = cancellable(log, args, t);
40+
*
41+
* const maxT = Math.max(t, cancelT)
42+
*
43+
* setTimeout(() => {
44+
* cancel()
45+
* }, cancelT)
46+
*
47+
* setTimeout(() => {
48+
* console.log(result) // [{"time":20,"returned":10}]
49+
* }, maxT + 15)
50+
*/

0 commit comments

Comments
 (0)