File tree 1 file changed +44
-0
lines changed
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 2715. Timeout Cancellation
2
+ // URL -> https://leetcode.com/problems/timeout-cancellation/
3
+
4
+ /**
5
+ * @param {Function } fn
6
+ * @param {Array } args
7
+ * @param {number } t
8
+ * @return {Function }
9
+ */
10
+ var cancellable = function ( fn , args , t ) {
11
+ let timer = setTimeout ( ( ) => {
12
+ fn ( ...args )
13
+ } , t )
14
+
15
+ return function ( ) {
16
+ clearTimeout ( timer )
17
+ }
18
+ } ;
19
+
20
+ /**
21
+ * const result = []
22
+ *
23
+ * const fn = (x) => x * 5
24
+ * const args = [2], t = 20, cancelT = 50
25
+ *
26
+ * const start = performance.now()
27
+ *
28
+ * const log = (...argsArr) => {
29
+ * const diff = Math.floor(performance.now() - start);
30
+ * result.push({"time": diff, "returned": fn(...argsArr)})
31
+ * }
32
+ *
33
+ * const cancel = cancellable(log, args, t);
34
+ *
35
+ * const maxT = Math.max(t, cancelT)
36
+ *
37
+ * setTimeout(() => {
38
+ * cancel()
39
+ * }, cancelT)
40
+ *
41
+ * setTimeout(() => {
42
+ * console.log(result) // [{"time":20,"returned":10}]
43
+ * }, maxT + 15)
44
+ */
You can’t perform that action at this time.
0 commit comments