Skip to main content
Back to problems
#2805
Medium JavaScript

Custom interval

84.7% acceptance
Mar 31, 2026
17
8
Function customInterval Given a function fn, a number delay and a number period, return a number id. customInterval is a function that should execute the provided function fn at intervals based on a linear pattern defined by the formula delay + period * count. The count in the formula represents the number of times the interval has been executed starting from an initial value of 0. Function customClearInterval Given the id. id is the returned value from the function customInterval. customClearInterval should stop executing provided function fn at intervals. Note: The setTimeout and setInterval functions in Node.js return an object, not a number.

Solution

TypeScript
Time O(1)
Space O(1)
LeetCode
solution.ts
const timers: Map<number, boolean> = new Map();
let nextId = 0;

function customInterval(fn: Function, delay: number, period: number): number {
  const id = nextId++;
  timers.set(id, true);
  let count = 0;
  function schedule() {
  const wait = delay + period * count;
  setTimeout(() => {
    if (!timers.has(id)) return;
    fn();
    count++;
    schedule();
  }, wait);
  }
  schedule();
  return id;
}

function customClearInterval(id: number): void {
  timers.delete(id);
}