写个防抖函数
复制问题

以下是一个用 JavaScript 实现的防抖函数示例:
function debounce(func, delay) {
let timer;
return function() {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
你可以这样使用它:
// 示例函数
function handleClick() {
console.log('按钮被点击了');
}
// 创建防抖后的函数
const debouncedClick = debounce(handleClick, 300);
// 模拟频繁调用
document.addEventListener('click', debouncedClick);
在上述代码中:
debounce
函数接受两个参数,func
是需要被防抖的目标函数,delay
是延迟的时间(以毫秒为单位)。- 它内部维护了一个
timer
变量来存储定时器 ID。 - 返回的新函数在每次被调用时,会清除之前设置的定时器(如果存在),然后重新设置一个新的定时器,在
delay
毫秒后执行目标函数func
。这样,在delay
时间间隔内如果再次调用该函数,之前的定时器会被清除,重新计时,只有在最后一次调用后的delay
毫秒后,目标函数才会真正执行,从而达到防抖的效果。
如果是在 Python 中实现类似功能,可以参考以下代码:
import time
def debounce(delay):
def decorator(func):
last_call_time = 0
def wrapper(*args, **kwargs):
nonlocal last_call_time
current_time = time.time()
if current_time - last_call_time >= delay:
result = func(*args, **kwargs)
last_call_time = current_time
return result
return wrapper
return decorator
使用方式如下:
@debounce(0.5) # 延迟 0.5 秒
def print_message():
print("防抖后的函数被调用了")
# 模拟频繁调用
for _ in range(5):
print_message()
time.sleep(0.1)
在 Python 的实现中,debounce
是一个装饰器工厂函数,它接受延迟时间 delay
作为参数,返回一个装饰器 decorator
。decorator
又返回一个包装函数 wrapper
,wrapper
会记录上次调用的时间,只有当距离上次调用的时间间隔超过 delay
时,才会执行原始函数。
重新生成
语音播放
复制回答