-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterval Cancellation.js
More file actions
52 lines (42 loc) · 1.48 KB
/
Interval Cancellation.js
File metadata and controls
52 lines (42 loc) · 1.48 KB
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
42
43
44
45
46
47
48
49
50
51
52
// Given a function fn, an array of arguments args, and an interval time t, return a cancel function cancelFn.
// After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked.
// setTimeout(cancelFn, cancelTimeMs)
// The function fn should be called with args immediately and then called again every t milliseconds until cancelFn is called at cancelTimeMs ms.
// Example 1:
// Input: fn = (x) => x * 2, args = [4], t = 35
// Output:
// [
// {"time": 0, "returned": 8},
// {"time": 35, "returned": 8},
// {"time": 70, "returned": 8},
// {"time": 105, "returned": 8},
// {"time": 140, "returned": 8},
// {"time": 175, "returned": 8}
// ]
// Explanation:
// const cancelTimeMs = 190;
// const cancelFn = cancellable((x) => x * 2, [4], 35);
// setTimeout(cancelFn, cancelTimeMs);
// Every 35ms, fn(4) is called. Until t=190ms, then it is cancelled.
// 1st fn call is at 0ms. fn(4) returns 8.
// 2nd fn call is at 35ms. fn(4) returns 8.
// 3rd fn call is at 70ms. fn(4) returns 8.
// 4th fn call is at 105ms. fn(4) returns 8.
// 5th fn call is at 140ms. fn(4) returns 8.
// 6th fn call is at 175ms. fn(4) returns 8.
// Cancelled at 190ms
// CODE
/**
* @param {Function} fn
* @param {Array} args
* @param {number} t
* @return {Function}
*/
var cancellable = function(fn, args, t) {
fn (...args)
let timer = setInterval(()=>{
fn (...args)
}, t)
let Canceltime = ()=>clearTimeout(timer)
return Canceltime
};