UniCoreFW

enhanced_debounce()

Enhanced debounce with max_wait support for better control.

Implementation

Args: func: The function to debounce wait: The delay in milliseconds max_wait: Maximum time to wait before forcing execution Returns: A debounced function with max_wait capability

Example

def api_call(): return "Called!" debounced = enhanced_debounce(api_call, 100, max_wait=500) # Function will execute after 100ms of inactivity or 500ms max

Expected output:

Source Code

def enhanced_debounce(func: Callable, wait: int, max_wait: Optional[int] = None) -> Callable: _validate_callable(func) wait_seconds = wait / 1000.0 max_wait_seconds = max_wait / 1000.0 if max_wait else None timer = None max_timer = None lock = threading.Lock() first_call_time = [None] result = [None] def debounced(*args, **kwargs): nonlocal timer, max_timer current_time = now() def execute(): nonlocal timer, max_timer with lock: if timer: timer.cancel() if max_timer: max_timer.cancel() timer = max_timer = None first_call_time[0] = None result[0] = func(*args, **kwargs) return result[0] with lock: # Cancel existing timer if timer: timer.cancel() # Set first call time if not set if first_call_time[0] is None: first_call_time[0] = current_time # type: ignore result[0] = func(*args, **kwargs) # Store initial result # Set max wait timer if specified if max_wait_seconds: max_timer = threading.Timer(max_wait_seconds, execute) max_timer.start() # Set regular debounce timer timer = threading.Timer(wait_seconds, execute) timer.start() return result[0] return _copy_function_metadata(debounced, func)