Python Logo

Python: Debounce utility function

import time ⏎
from functools import wraps
from threading import Timer

def debounce(wait):
	def decorator(func):
		last_call = 0
		timer = None
		@wraps(func)
		def debounced(*args, **kwargs):
			nonlocal last_call, timer
			current_time = time.time()
			if timer:
				timer.cancel()
			if current_time - last_call >= wait:
				last_call = current_time
				return func(*args, **kwargs)
			else:
				timer = Timer(wait - (current_time - last_call), func, args, kwargs)
				timer.start()
		return debounced
	return decorator
Accuracy
100 %
0 Mistakes
CPM
0
Average: 0 CPM
Time
0.000 s
Personal best: 120.452 s