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: Function Execution TimelineInput: fn=()=>x++, args=[2], t=20ms, cancelTimeMs=50msCallCallCallCancelt=0mst=20mst=40mst=50msreturns 2returns 3returns 4Output:[{"time":0,"returned":2},{"time":20,"returned":3},{"time":40,"returned":4}]
Understanding the Visualization
1
Input
Function fn, args=[2], interval t=20ms, cancel at 50ms
2
Process
Call immediately, then every 20ms until cancellation
3
Output
Array of {time, returned} objects for each execution
Key Takeaway
🎯 Key Insight: Use setInterval for recurring execution and clearInterval for clean cancellation
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