Skip to content

Instantly share code, notes, and snippets.

@sosukeinu
Forked from kylebebak/debounce.py
Created July 13, 2018 21:03
Show Gist options
  • Save sosukeinu/7c3dfeaa394a14a773c379bec6f88591 to your computer and use it in GitHub Desktop.
Save sosukeinu/7c3dfeaa394a14a773c379bec6f88591 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment