Skip to main content
Back to problems
#2725
Easy JavaScript

Interval cancellation

84.8% acceptance
Mar 2, 2026
214
99
Given a function fn, an array of arguments args, and an interval time t, return a cancel function cancelFn. After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked. setTimeout(cancelFn, cancelTimeMs) The function fn should be called with args immediately and then called again every t milliseconds until cancelFn is called at cancelTimeMs ms.

Solution

TypeScript
Time O(1)
Space O(1)
LeetCode
solution.ts
type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };
type Fn = (...args: JSONValue[]) => void;

function cancellable(fn: Fn, args: JSONValue[], t: number): Function {
  fn(...args);
  const interval = setInterval(() => fn(...args), t);
  return function () {
  clearInterval(interval);
  };
}

/**
 *  const cancel = cancellable(log, args, t);
 *  setTimeout(cancel, cancelTimeMs);
 */