LeetCode Problem Workspace

Timeout Cancellation

Learn to implement timeout cancellation logic for function execution using a custom cancel function.

category

0

Topics

code_blocks

2

Code langs

hub

0

Related

Practice Focus

Easy · Timeout Cancellation core interview pattern

bolt

Answer-first summary

Learn to implement timeout cancellation logic for function execution using a custom cancel function.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Timeout Cancellation core interview pattern

Try AiBox Copilotarrow_forward

In the "Timeout Cancellation" problem, you need to return a cancel function that delays the execution of a function by a specified time. The cancel function should trigger cancellation after a given timeout, effectively controlling when the function executes. The key challenge is managing the timing and ensuring the function does not execute after cancellation.

Problem Statement

You are given a function fn, an array of arguments args, and a timeout t in milliseconds. Your goal is to return a cancel function cancelFn.

The function cancelFn should be invoked after a delay of cancelTimeMs milliseconds. Initially, the execution of the function fn should be delayed by t milliseconds, and the cancel function should stop execution if invoked before the delay ends.

Examples

Example 1

Input: See original problem statement.

Output: See original problem statement.

setTimeout(cancelFn, cancelTimeMs)

Example 2

Input: fn = (x) => x * 5, args = [2], t = 20

Output: [{"time": 20, "returned": 10}]

const cancelTimeMs = 50; const cancelFn = cancellable((x) => x * 5, [2], 20); setTimeout(cancelFn, cancelTimeMs);

The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened after the execution of fn(2) at 20ms.

Example 3

Input: fn = (x) => x2, args = [2], t = 100

Output: []

const cancelTimeMs = 50; const cancelFn = cancellable((x) => x2, [2], 100); setTimeout(cancelFn, cancelTimeMs);

The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened before the execution of fn(2) at 100ms, resulting in fn(2) never being called.

Constraints

  • fn is a function
  • args is a valid JSON array
  • 1 <= args.length <= 10
  • 20 <= t <= 1000
  • 10 <= cancelTimeMs <= 1000

Solution Approach

Managing Execution Timing

The problem involves timing the execution of a function using setTimeout. Initially, the function fn is called after the specified delay t, but if the cancel function is called before t expires, it should prevent fn from executing. This is managed by scheduling a timeout to invoke the cancel function.

Implementing the Cancel Function

To implement the cancel function, you need to schedule the cancellation of the original function using setTimeout again. This secondary timeout (cancelTimeMs) ensures that if the cancel function is invoked before the first timeout expires, the execution is halted.

Handling Edge Cases

Special cases include ensuring that the cancel function is only invoked once and that it interacts correctly with the timing of fn. For instance, if the cancel function is triggered before t, fn should never execute. If t expires first, fn should execute normally.

Complexity Analysis

Metric Value
Time **
Space **

The time complexity is O(1) since the logic involves setting timeouts and no iterative processing. The space complexity is O(1) as we are only using a fixed number of variables, regardless of input size.

What Interviewers Usually Probe

  • The candidate should demonstrate an understanding of setTimeout and timing functions.
  • Look for an efficient approach to canceling execution without unnecessary delays.
  • Check if the candidate correctly handles edge cases, such as the cancel function being invoked after the timeout has expired.

Common Pitfalls or Variants

Common pitfalls

  • Failing to handle the cancel function being invoked after t has already expired.
  • Incorrectly managing the timing of the cancel function, causing unexpected behavior.
  • Not ensuring that cancelFn is invoked only once and that fn is not called multiple times.

Follow-up variants

  • Implement the solution using promises instead of callbacks.
  • Extend the problem to support multiple cancel functions, each for different timeouts.
  • Add a feature to allow cancellation after multiple delays.

FAQ

What is the core interview pattern for the "Timeout Cancellation" problem?

The core pattern revolves around managing the execution timing of a function and implementing a cancel mechanism using setTimeout to prevent its execution.

How does setTimeout interact with the cancel function in this problem?

The setTimeout function is used to delay the execution of the original function, and a second setTimeout is used to invoke the cancel function after the specified cancel time to prevent the original function from executing.

What happens if the cancel function is triggered after the timeout expires?

If the cancel function is invoked after the timeout expires, the original function fn will already have executed, so the cancellation has no effect.

How do I prevent the function from executing if the cancel function is invoked?

You need to ensure that the cancel function prevents the execution of fn by canceling or stopping the setTimeout call before fn is triggered.

What edge cases should I consider in the "Timeout Cancellation" problem?

Consider scenarios where the cancel function is called before or after the timeout expires, as well as cases where fn should not execute due to cancellation.

terminal

Solution

Solution 1

#### TypeScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * @param {Function} fn
 * @param {Array} args
 * @param {number} t
 * @return {Function}
 */
var cancellable = function (fn, args, t) {
    const timer = setTimeout(() => fn(...args), t);
    return () => {
        clearTimeout(timer);
    };
};

/**
 *  const result = []
 *
 *  const fn = (x) => x * 5
 *  const args = [2], t = 20, cancelT = 50
 *
 *  const start = performance.now()
 *
 *  const log = (...argsArr) => {
 *      const diff = Math.floor(performance.now() - start);
 *      result.push({"time": diff, "returned": fn(...argsArr))
 *  }
 *
 *  const cancel = cancellable(log, args, t);
 *
 *  const maxT = Math.max(t, cancelT)
 *
 *  setTimeout(() => {
 *     cancel()
 *  }, cancelT)
 *
 *  setTimeout(() => {
 *     console.log(result) // [{"time":20,"returned":10}]
 *  }, maxT + 15)
 */
Timeout Cancellation Solution: Timeout Cancellation core interview p… | LeetCode #2715 Easy