Timeout Cancellation

javascript, async, leetcode2715

Main project image

The setTimeout() sets a timer which executes a function once the timer expires. The general syntax looks like this:

setTimeout(functionRef, delay)

To cancel a setTimeout(), the clearTimeout() method can be used which is demonstrated below. Initially, the execution of fn is delayed by t ms using setTimeout().

After a delay of cancelTImeMs, the return cancel function cancelFn will be invoked.

setTimeout(cancelFn, cancelTimeMs)

If the cancelFn is invoked it should cancel the delayed execution of fn or otherwise, continue executing the function. In actual production, the timer could be a long running API task such as an external API request that is awaiting.


var cancellable = function(fn, args, t) {
    const timer = setTimeout(() => fn(...args), t)

    return async function cancelFn(...args) {
     clearTimeout(timer) // cancels the timeout
    } 
};

/**
 *  const result = [];
 *
 *  const fn = (x) => x * 5;
 *  const args = [2], t = 20, cancelTimeMs = 50;
 *
 *  const start = performance.now();
 *
 *  const log = (...argsArr) => {
 *      const diff = Math.floor(performance.now() - start);
 *      result.push({"time": diff, "returned": fn(...argsArr)});
 *  }
 *       
 *  const cancel = cancellable(log, args, t);
 *
 *  const maxT = Math.max(t, cancelTimeMs);
 *           
 *  setTimeout(cancel, cancelTimeMs); // after a delay, the cancel function is invoked
 *
 *  setTimeout(() => {
 *      console.log(result); // [{"time":20,"returned":10}]
 *  }, maxT + 15)
 */