1
+ // Given a function fn, an array of arguments args, and an
2
+ // interval time t, return a cancel function cancelFn.
3
+
4
+ // The function fn should be called with args immediately and then
5
+ // called again every t milliseconds until cancelFn is called at cancelT ms.
6
+
7
+ /**
8
+ * @param {Function } fn
9
+ * @param {Array } args
10
+ * @param {number } t
11
+ * @return {Function }
12
+ */
13
+ var cancellable = function ( fn , args , t ) {
14
+ fn ( ...args ) ;
15
+ let timer = setInterval ( ( ) => fn ( ...args ) , t ) ;
16
+
17
+ let cancelFn = ( ) => clearInterval ( timer ) ;
18
+ return cancelFn ;
19
+ } ;
20
+
21
+ /**
22
+ * const result = []
23
+ *
24
+ * const fn = (x) => x * 2
25
+ * const args = [4], t = 35, cancelT = 190
26
+ *
27
+ * const start = performance.now()
28
+ *
29
+ * const log = (...argsArr) => {
30
+ * const diff = Math.floor(performance.now() - start)
31
+ * result.push({"time": diff, "returned": fn(...argsArr)})
32
+ * }
33
+ *
34
+ * const cancel = cancellable(log, args, t);
35
+ *
36
+ * setTimeout(() => {
37
+ * cancel()
38
+ * }, cancelT)
39
+ *
40
+ * setTimeout(() => {
41
+ * console.log(result) // [
42
+ * // {"time":0,"returned":8},
43
+ * // {"time":35,"returned":8},
44
+ * // {"time":70,"returned":8},
45
+ * // {"time":105,"returned":8},
46
+ * // {"time":140,"returned":8},
47
+ * // {"time":175,"returned":8}
48
+ * // ]
49
+ * }, cancelT + t + 15)
50
+ */
0 commit comments