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
Understanding the Visualization
1
Input
Function, arguments, and timeout delay
2
Process
Schedule function execution and provide cancel mechanism
3
Output
Either function executes or cancellation message
Key Takeaway
🎯 Key Insight: JavaScript's setTimeout/clearTimeout provides precise control over scheduled function execution with proper cancellation mechanism
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code