We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Timeout Cancellation

Number: 2821

Difficulty: Easy

Paid? No

Companies: Adobe


Problem Description

Design a function that takes a function (fn), an array of arguments (args), and a delay time t in milliseconds. The function should initially schedule fn to execute after t milliseconds with the provided arguments. It should also return a cancel function (cancelFn). If cancelFn is called before t milliseconds have elapsed, the scheduled execution of fn is canceled. If not, fn is executed with args when t milliseconds pass.


Key Insights

  • Schedule the execution of fn after a delay using a timer mechanism.
  • Return a cancel function that can cancel the pending execution before the timer expires.
  • Use timer IDs or scheduling handles to manage the cancellation.
  • The approach has constant time and space complexity since no extra data structures or iterative processes are required.

Space and Time Complexity

Time Complexity: O(1) – Scheduling and canceling the timer each require constant time. Space Complexity: O(1) – Only a few variables are maintained regardless of input size.


Solution

We schedule the execution of the provided function fn using a timer (such as setTimeout in JavaScript or threading.Timer in Python) for t milliseconds. The function returns a cancel function that, when invoked before the timer elapses, cancels the timer to ensure fn never executes. In languages without built-in timer cancellation primitives, we simulate this behavior using thread-based sleep mechanisms and shared cancellation flags. Key techniques include:

  • Scheduling a delayed task for fn.
  • Storing the timer or future identifier.
  • Providing a cancel function that can clear the timer or set a cancellation flag. This approach guarantees that fn is called with the provided arguments if and only if the cancel function is not invoked in time.

Code Solutions

import threading

def cancellable(fn, args, t):
    # Create a timer that will execute fn with unpacked args after t milliseconds.
    timer = threading.Timer(t / 1000.0, lambda: fn(*args))
    timer.start()  # Start the timer

    # Define and return the cancel function that cancels the timer.
    def cancelFn():
        timer.cancel()
    return cancelFn

# Example usage:
# cancelFn = cancellable(lambda x: print(x * 5), [2], 20)
# threading.Timer(0.05, cancelFn).start()  # Cancel after 50ms if desired.
← Back to All Questions