[Easy] LeetCode JS 30 - 2715. Timeout Cancellation

March 5, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2715. Timeout Cancellation

Question Prompt

Given a function fn, an array of arguments args, and a timeout t in milliseconds, return a cancel function cancelFn.

After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked.

setTimeout(cancelFn, cancelTimeMs)

Initially, the execution of the function fn should be delayed by t milliseconds.

If, before the delay of t milliseconds, the function cancelFn is invoked, it should cancel the delayed execution of fn. Otherwise, if cancelFn is not invoked within the specified delay tfn should be executed with the provided args as arguments.

Input: fn = (x) => x * 5, args = [2], t = 20
Output: [{"time": 20, "returned": 10}]
Explanation:
const cancelTimeMs = 50;
const cancelFn = cancellable((x) => x * 5, [2], 20);
setTimeout(cancelFn, cancelTimeMs);

The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened after the execution of fn(2) at 20ms.

Solutions

Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!

First, create a function that takes three parameters fn , args , and t . Then, create a variable to store the unique identifier returned by the setTimeout function. This identifier is crucial for canceling the scheduled execution.

We use setTimeout to schedule the execution of fn. Inside the setTimeout callback, we execute the function fn and use the spread operator (...) to pass the elements of the args array as individual arguments.

Lastly, return a**cancelFn.** This is the function that will be returned to provide the cancellation capability. Inside cancelFn, we use clearTimeout with the timeoutId to stop the scheduled execution of fn.

var cancellable = function (fn, args, t) {
  const timerId = setTimeout(() => {
    fn(...args);
  }, t);
  return function cancelFn() {
    clearTimeout(timerId);
  };
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee