python函数防抖与节流

防抖:

几秒内只允许外部调用一次,调越多等越长

节流:

几秒内只会内部运行一次,到点后才会再运行,比如贤者时间

代码实现

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)

最后输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bar called args= () kwargs= {'funcName': 'throtted', 'x': 0, 'y': 0}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 30, 'y': 249}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 77, 'y': 213}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 147, 'y': 944}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 200, 'y': 291}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 261, 'y': 536}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 299, 'y': 930}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 362, 'y': 893}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 396, 'y': 957}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 477, 'y': 723}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 559, 'y': 93}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 627, 'y': 148}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 692, 'y': 625}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 774, 'y': 30}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 858, 'y': 866}
bar called args= () kwargs= {'funcName': 'throtted', 'x': 923, 'y': 414}
bar called args= (3,) kwargs= {'funcName': 'deb_thi'}

python函数防抖与节流
https://www.hakurei.org.cn/2023/02/01/py-debounce/
作者
zjkimin
发布于
2023年2月1日
更新于
2023年2月1日
许可协议