Interval Cancellation - Problem

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.

Input & Output

Example 1 — Basic Interval
$ Input: fn = () => x++, args = [2], t = 20, cancelTimeMs = 50
Output: [{"time":0,"returned":2},{"time":20,"returned":3},{"time":40,"returned":4}]
💡 Note: Function called immediately at t=0 returning 2, then at t=20 returning 3, then at t=40 returning 4. Cancelled before t=60.
Example 2 — Short Interval
$ Input: fn = () => x++, args = [5], t = 25, cancelTimeMs = 30
Output: [{"time":0,"returned":5},{"time":25,"returned":6}]
💡 Note: Function called at t=0 returning 5, then at t=25 returning 6. Next call would be at t=50 but cancelled at t=30.
Example 3 — Immediate Cancel
$ Input: fn = () => x++, args = [1], t = 100, cancelTimeMs = 10
Output: [{"time":0,"returned":1}]
💡 Note: Only the immediate call at t=0 executes returning 1. Cancelled at t=10 before first interval at t=100.

Constraints

  • 1 ≤ t ≤ 103
  • 1 ≤ cancelTimeMs ≤ 104
  • fn is a JavaScript function
  • args is an array of valid JavaScript values

Visualization

Tap to expand
Interval Cancellation INPUT fn (function) () => x++ args (array) [2] t (interval) 20ms cancelTimeMs 50ms Timeline 0ms call 20ms call 40ms call 50ms cancel 60ms Initial x value: 2 Increments each call ALGORITHM STEPS 1 Call fn Immediately Execute fn(args) at t=0 x++ --> returns 2 2 Set Up Interval setInterval(fn, t) interval every 20ms 3 Repeat Calls At 20ms: x++ --> 3 At 40ms: x++ --> 4 4 Cancel at 50ms clearInterval(intervalId) Stop all future calls const result = fn(args); const id = setInterval( () => fn(args), t); return () => clearInterval(id); FINAL RESULT Function calls recorded: 1 time: 0ms returned: 2 2 time: 20ms returned: 3 3 time: 40ms returned: 4 Cancelled at 50ms - No more calls Output Array: [{0,2},{20,3},{40,4}] Key Insight: The function must be called IMMEDIATELY (at t=0), then setInterval handles repeated calls. The cancelFn returns clearInterval to stop future executions. Calls at 0, 20, 40ms occur before cancellation at 50ms. The 60ms call never happens because interval is cleared. TutorialsPoint - Interval Cancellation | setInterval with clearInterval
Asked in
Meta 25 Amazon 20
23.0K Views
Medium Frequency
~15 min Avg. Time
850 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