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

Interval Cancellation

Number: 2862

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

You are given a function fn, an array of arguments args, and an interval time t (in milliseconds). The function fn should be called immediately with args and then repeatedly every t milliseconds. A cancel function cancelFn is returned, and when cancelFn is eventually invoked (for example, via setTimeout(cancelFn, cancelTimeMs)), the repeated execution of fn stops.


Key Insights

  • The initial call to fn happens immediately.
  • Subsequent calls happen at a fixed interval t until cancellation.
  • A cancellation mechanism is needed to stop future scheduled calls.
  • In different languages, this is typically achieved using functions like setInterval/clearInterval (JavaScript) or background threads/timers (Python, C++, Java).

Space and Time Complexity

Time Complexity: O(1) per invocation (ignoring the repeated periodic timer, which is an asynchronous scheduling mechanism).
Space Complexity: O(1) aside from the overhead of the timer or thread handling the periodic calls.


Solution

We create a mechanism that immediately calls fn with the provided args, then starts a periodic scheduler that repeatedly invokes fn every t milliseconds. The scheduler runs asynchronously (using setInterval in JavaScript, a background thread in Python, etc.). A cancel function is returned that, when called, stops the scheduler. An important point is to ensure that the cancel mechanism correctly stops the scheduling to avoid additional unnecessary calls or resource leaks.


Code Solutions

Below are implementations in Python, JavaScript, C++, and Java.

import threading
import time

def cancellable(fn, args, t):
    # Immediately call fn with the given args.
    fn(*args)
    
    # Create an event to signal cancellation.
    stop_event = threading.Event()
    
    # Define a function that will repeatedly call fn at interval t (converted to seconds).
    def run_periodically():
        # Loop until the cancellation event is set.
        while not stop_event.wait(t / 1000.0):
            fn(*args)
    
    # Start the periodic function in a daemon thread.
    thread = threading.Thread(target=run_periodically)
    thread.daemon = True
    thread.start()
    
    # Define and return the cancellation function.
    def cancelFn():
        stop_event.set()
    
    return cancelFn

# Example usage:
# def my_fn(x): 
#     print("Called:", x)
# cancel_fn = cancellable(my_fn, [4], 35)
# time.sleep(0.19)  # simulate cancelTimeMs as 190ms
# cancel_fn()
← Back to All Questions