Conclusion first
I could not solve it within the time limit I set (40 minutes). So I learned from the top-rank solution from Giacomo Sorbi, got help from a friend. This problem is similar to the problem 2627. Debounce.
Solution
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Fn = (...args: JSONValue[]) => void
function cancellable(fn: Fn, args: JSONValue[], t: number): Function {
const id = setTimeout(() => fn(...args), t);
return () => clearTimeout(id);
};
Explanation
The goal is to return a function that can be called. Once the function is called, it should cancel the timer that was previously set using setTimeout()
in the function cancellable
.
If the function cancellable
is called, the timer inside the function cancellable
will start counting down.
First, create a function variable called cancel
and assign it the cancellable
function:
const cancel = cancellable(log, 'Hello', 5000);
Now that we have our cancel
function, we can use it to cancel the timer inside the cancellable
function:
cancel();
The magic happens because the cancellable
function returns a function that can be used to cancel its internal timer:
const id = setTimeout(() => fn(...args), t);
return () => clearTimeout(id);
Top comments (0)