防抖函数的作用是在短时间内频繁触发的事件只执行一次,节流函数的作用是在连续触发的事件中间隔一段时间执行一次。
以下是防抖函数和节流函数的示例代码:
防抖函数:
import time
def debounce(func, wait):
timer = None
def wrapper(*args, **kwargs):
nonlocal timer
if timer:
clearTimeout(timer)
timer = setTimeout(func, wait, *args, **kwargs)
return wrapper
节流函数:
import time
def throttle(func, wait):
last_executed_time = 0
def wrapper(*args, **kwargs):
nonlocal last_executed_time
current_time = time.time()
if current_time - last_executed_time > wait:
func(*args, **kwargs)
last_executed_time = current_time
return wrapper
注意,以上代码是用Python语言来实现的,并参考了JavaScript中的setTimeout和clearTimeout函数的概念。在实际使用中,需要根据具体的编程环境来调整代码。