Skip to content

Instantly share code, notes, and snippets.

@devrim
Created December 7, 2023 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devrim/fdfada5aa80501b39b96f20810a51a6e to your computer and use it in GitHub Desktop.
Save devrim/fdfada5aa80501b39b96f20810a51a6e to your computer and use it in GitHub Desktop.
python throttling
import time
def create_throttled_function(func, period):
"""Creates a throttled version of the given function that can only be called once every 'period' seconds."""
last_called = [0]
def throttled_function(*args, **kwargs):
nonlocal last_called
current_time = time.time()
if current_time - last_called[0] >= period:
last_called[0] = current_time
return func(*args, **kwargs)
return throttled_function
# Example usage
def my_function():
print("Function is called")
throttled_my_function = create_throttled_function(my_function, 2)
# Testing the throttled function
throttled_my_function() # This call will work
time.sleep(1)
throttled_my_function() # This call will be ignored since it's within 2 seconds of the last call
time.sleep(2)
throttled_my_function() # This call will work, as it's 2 seconds after the last call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment