手写防抖
js
123456789101112131415
function debounce(func, wait) {
var timer = null
return function (...args){
if(timer)clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this,args)
},wait)
}
}
// 测试用例:
const handleSearch = debounce((query) => console.log("发送搜索请求:", query), 500);
handleSearch("A");
handleSearch("AB");
handleSearch("ABC"); // 只有最后这个 "ABC" 会在 500ms 后被打印