File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ function cancellable(fn: Function, args: any[], t: number): Function {
2+ const cancelFn: any = () => clearTimeout(timer);
3+ const timer: ReturnType<typeof setTimeout> = setTimeout(() => {
4+ fn(...args);
5+ }, t);
6+ return cancelFn;
7+ };
8+
9+ /**
10+ * const result = []
11+ *
12+ * const fn = (x) => x * 5
13+ * const args = [2], t = 20, cancelT = 50
14+ *
15+ * const start = performance.now()
16+ *
17+ * const log = (...argsArr) => {
18+ * const diff = Math.floor(performance.now() - start);
19+ * result.push({"time": diff, "returned": fn(...argsArr)})
20+ * }
21+ *
22+ * const cancel = cancellable(log, args, t);
23+ *
24+ * const maxT = Math.max(t, cancelT)
25+ *
26+ * setTimeout(() => {
27+ * cancel()
28+ * }, cancelT)
29+ *
30+ * setTimeout(() => {
31+ * console.log(result) // [{"time":20,"returned":10}]
32+ * }, maxT + 15)
33+ */
You can’t perform that action at this time.
0 commit comments