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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs