1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| from threading import Timer
class setTimeOut: _timer = Timer def __init__(self,fn,delay,args=None,kwargs=None) -> None: self._timer = Timer(delay,fn,args,kwargs) self._timer.start() def clear(self): self._timer.cancel() def is_finished(self): return self._timer.finished.is_set() class debounce: timer:setTimeOut = None def __init__(self,func,delay) -> None: self.func = func self.delay = delay def __call__(self,*args,**kwargs): if self.timer is not None: self.timer.clear() self.timer=setTimeOut(self.func,self.delay,args,kwargs)
class throttle: timer:setTimeOut = None
def __init__(self,func,delay) -> None: self.func = func self.delay = delay def __call__(self,*args,**kwargs): if (self.timer is None) or self.timer.is_finished(): self.timer=setTimeOut(self.func,self.delay,args,kwargs)
def bar(*args,**kwargs): print('bar called','args=',args,'kwargs=',kwargs)
bar_debed = debounce(bar,2) bar_debed(1,funcName='deb_first') bar_debed(2,funcName='deb_sec') bar_debed(3,funcName='deb_thi')
bar_throtted = throttle(bar,0.01) for x in range(1000): for y in range(1000): bar_throtted(funcName = 'throtted' ,x = x,y = y)
|