Timeout Cancellation - Problem

Given a function fn, an array of arguments args, and a timeout t in milliseconds, return a cancel function cancelFn.

After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked.

setTimeout(cancelFn, cancelTimeMs)

Initially, the execution of the function fn should be delayed by t milliseconds.

If, before the delay of t milliseconds, the function cancelFn is invoked, it should cancel the delayed execution of fn. Otherwise, if cancelFn is not invoked within the specified delay t, fn should be executed with the provided args as arguments.

Input & Output

Example 1 — Function Gets Cancelled
$ Input: fn = "sum", args = [1,2,3], t = 100ms, cancelTimeMs = 50ms
Output: "Function was cancelled"
💡 Note: Cancel function is called after 50ms, before the 100ms timeout, so the function never executes
Example 2 — Function Executes
$ Input: fn = "mult", args = [2,4], t = 50ms, cancelTimeMs = 100ms
Output: Function executes and returns 8
💡 Note: Function executes after 50ms because cancel isn't called until 100ms
Example 3 — Immediate Cancellation
$ Input: fn = "sum", args = [5], t = 1000ms, cancelTimeMs = 0ms
Output: "Function was cancelled"
💡 Note: Cancel is called immediately (0ms), preventing execution

Constraints

  • fn is a function that takes arguments args
  • 0 ≤ args.length ≤ 10
  • 10 ≤ t ≤ 1000
  • 0 ≤ cancelTimeMs ≤ 1000

Visualization

Tap to expand
Timeout Cancellation - clearTimeout Approach INPUT fn = "sum" args array: 1 2 3 t = 100ms (execution delay) cancelTimeMs = 50ms (cancel trigger time) Timeline: 0ms 50ms CANCEL 100ms ALGORITHM STEPS 1 Setup setTimeout Schedule fn to run after t ms timer = setTimeout(fn, t) 2 Create cancelFn Return function that clears timer cancelFn = clearTimeout 3 Cancel Invoked At 50ms: cancelFn() called 50ms < 100ms --> CANCEL 4 Clear Timer clearTimeout prevents fn exec clearTimeout(timer) FINAL RESULT Output: "Function was cancelled" Why? cancelTime 50ms < timeout t 100ms Cancel triggered BEFORE fn could execute. sum(1,2,3) never runs! CANCELLED Key Insight: The clearTimeout approach stores the timer ID returned by setTimeout. When cancelFn is invoked, it calls clearTimeout(timerId) which removes the scheduled callback from the event loop queue. If cancelTimeMs < t, the function is cancelled. If cancelTimeMs >= t, the function executes normally. TutorialsPoint - Timeout Cancellation | clearTimeout Approach
Asked in
Google 25 Microsoft 20 Facebook 15
24.0K Views
Medium Frequency
~15 min Avg. Time
890 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