Custom Interval - Problem

Implement two functions to create and manage custom intervals:

Function customInterval: Given a function fn, a number delay and a number period, return a number id. The function should execute the provided function fn at intervals based on a linear pattern defined by the formula delay + period * count. The count represents the number of times the interval has been executed starting from an initial value of 0.

Function customClearInterval: Given the id returned from customInterval, stop executing the provided function fn at intervals.

Note: The setTimeout and setInterval functions in Node.js return an object, not a number.

Input & Output

Example 1 — Basic Custom Interval
$ Input: delay = 100, period = 50
Output: ["customInterval", "customClearInterval"]
💡 Note: Creates custom interval functions where first execution happens at 100ms, second at 150ms, third at 200ms, following the pattern delay + period * count
Example 2 — Zero Period
$ Input: delay = 200, period = 0
Output: ["customInterval", "customClearInterval"]
💡 Note: With period = 0, all executions happen at the same interval of 200ms since delay + 0 * count = 200
Example 3 — Large Period
$ Input: delay = 50, period = 100
Output: ["customInterval", "customClearInterval"]
💡 Note: Executions at 50ms, 150ms, 250ms, 350ms - rapidly increasing intervals

Constraints

  • 0 ≤ delay ≤ 104
  • 0 ≤ period ≤ 104
  • Function fn will be provided at runtime

Visualization

Tap to expand
Custom Interval Implementation INPUT Parameters delay = 100 period = 50 Function (fn) () => callback() Execution Timeline 100ms 150ms 200ms ... Formula: delay + period * count count: 0, 1, 2, 3... ALGORITHM STEPS 1 Initialize Create unique ID Set count = 0 2 Calculate Next Time next = delay + period * count 100 + 50 * 0 = 100ms 3 Schedule Execution setTimeout(fn, next) Increment count++ 4 Loop or Clear Repeat step 2-3 Until clearInterval Storage Map Map<id, timeoutId> Track active intervals FINAL RESULT Exported Functions customInterval customClearInterval Output: ["customInterval", "customClearInterval"] Execution Example Call 1: t=100ms (100+50*0) Call 2: t=150ms (100+50*1) Call 3: t=200ms (100+50*2) Call 4: t=250ms (100+50*3) ... continues until cleared OK Linear interval pattern Key Insight: Unlike setInterval with fixed delays, customInterval uses a linear formula (delay + period * count) where each subsequent execution waits progressively longer. Store timeout IDs in a Map to enable clearTimeout when customClearInterval is called. This creates an accelerating gap pattern. TutorialsPoint - Custom Interval | Enhanced Implementation
Asked in
Google 25 Facebook 18
12.5K Views
Medium Frequency
~15 min Avg. Time
420 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen