UniCoreFW

throttle()

Creates a function that is restricted to execute `func` once per `wait` milliseconds.

Implementation

Parameters: func: Callable[[Any], R] The function to throttle. wait: int The number of milliseconds to wait. Returns: Callable[[Any], R] A new function that wraps `func`, ensuring it is only called once per `wait` milliseconds.

Example

def print_time(): print(time.time()) throttled = throttle(print_time, 1000) throttled() # Prints time throttled() # Does nothing time.sleep(1) throttled() # Prints time

Expected output: Function that executes at most once per second

Source Code

def throttle(func, wait): last_called = 0.0 last_result = None wait_s = wait / 1000.0 def wrapper(*args, **kwargs): nonlocal last_called, last_result now = time.time() if now - last_called > wait_s: last_called = now last_result = func(*args, **kwargs) return last_result return wrapper