-
Notifications
You must be signed in to change notification settings - Fork 0
/
day15_promises-set&clearIntervals.js
53 lines (50 loc) · 1.52 KB
/
day15_promises-set&clearIntervals.js
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
53
/**
* @param {Function} fn
* @param {Array} args
* @param {number} t
* @return {Function}
*/
var cancellable = function(fn, args, t) {
//call fn immedietly
fn(...args);
// call setInterval, which is set to call fn after t amount of time
// this is like "for" function with time function
let timeout = setInterval(function() {
fn(...args);
}, t);
// define a clearInterval built in js function to stop the setInterval repeater
let cancelFn = function() {
clearInterval(timeout);
};
return cancelFn;
};
/**
* const result = []
*
* const fn = (x) => x * 2
* const args = [4], t = 20, cancelT = 110
*
* 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);
*
* setTimeout(() => {
* cancel()
* }, cancelT)
*
* setTimeout(() => {
* console.log(result) // [
* // {"time":0,"returned":8},
* // {"time":20,"returned":8},
* // {"time":40,"returned":8},
* // {"time":60,"returned":8},
* // {"time":80,"returned":8},
* // {"time":100,"returned":8}
* // ]
* }, cancelT + t + 15)
*/