-
-
Save sosukeinu/7c3dfeaa394a14a773c379bec6f88591 to your computer and use it in GitHub Desktop.
Simple Python 3 debounce implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
@debounce(3) | |
def hi(name): | |
print('hi {}'.format(name)) | |
hi('dude') | |
time.sleep(1) | |
hi('mike') | |
time.sleep(1) | |
hi('mary') | |
time.sleep(1) | |
hi('jane') | |
""" | |
import time | |
def debounce(s): | |
"""Decorator ensures function that can only be called once every `s` seconds. | |
""" | |
def decorate(f): | |
t = None | |
def wrapped(*args, **kwargs): | |
nonlocal t | |
t_ = time.time() | |
if t is None or t_ - t >= s: | |
result = f(*args, **kwargs) | |
t = time.time() | |
return result | |
return wrapped | |
return decorate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment