DEV Community

Jen C.
Jen C.

Posted on

LeetCode - Solution for 2715. Timeout Cancellation

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);
};
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Now that we have our cancel function, we can use it to cancel the timer inside the cancellable function:

cancel();
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Reference

  1. https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout

Top comments (0)