Skip to content

Instantly share code, notes, and snippets.

@kylebebak
Last active August 30, 2023 12:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kylebebak/ee67befc156831b3bbaa88fb197487b0 to your computer and use it in GitHub Desktop.
Save kylebebak/ee67befc156831b3bbaa88fb197487b0 to your computer and use it in GitHub Desktop.
Simple Python 3 debounce implementation
"""
@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
Copy link

Ajk4 commented Jan 3, 2019

It's not a debounce. It's a throttle

@kylebebak
Copy link
Author

@Ajk4
Thanks, you're totally right!

@yurenchen000
Copy link

yurenchen000 commented Feb 18, 2022

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