Last active
August 30, 2023 12:46
-
-
Save kylebebak/ee67befc156831b3bbaa88fb197487b0 to your computer and use it in GitHub Desktop.
Simple Python 3 debounce implementation
This file contains hidden or 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 |
@Ajk4
Thanks, you're totally right!
some test:
@debounce(2)
def hi(name):
print('hi {}'.format(name))
for i in range(5):
hi(f' {i}')
print(f' {i} {time.time()}')
time.sleep(0.8)
outs:
hi 0
0 1645192096.4046965
1 1645192097.2055717
2 1645192098.006468
hi 3
3 1645192098.807511
4 1645192099.6083152
have to say, if someone want to
filter out process jitter, get the final state
this exactly not what they want.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's not a
debounce
. It's athrottle