在用户执行某种特定操作时(频率很高),我们没必要每次都监听这个函数,如淘宝搜索栏,百度搜索栏快速输入值检索过滤,可以定义多少ms后执行一次,减少http的请求频率
function debounce(func, wait) {
let timer;
return function() {
let context = this; // 注意 this 指向
let args = arguments; // arguments中存着e
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
function search() {
console.log("可以执行你啦")
}
document.addEventListener("scroll",debounce(search,500))
//document.getElementById('input-serach').addEventListener('input',debounce(search,500))