2715. Timeout Cancellation

2715. Timeout Cancellation

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

After a delay of t, fn should be called with args passed as parameters unless cancelFn was invoked before the delay of t milliseconds elapses, specifically at cancelT ms. In that case, fn should never be called.

  1. 寫出一個會回傳 cancelFn 的 function。

  2. function 會先設置一個 timer 再回傳出一個會清除該 timercancelFn

  3. 之後只要 clearTimeout function 被執行的時間低於 timer 所設置的時間, timer 就不會發生。

var cancellable = function (fn, args, t) {
  const timer = setTimeout(() => {
    fn(...args);
  }, t);
  return function cancelFn() {
    clearTimeout(timer);
  };
};