防抖 (debounce) 函式是指,将多次操作优化为,只在最后一次执行。具体来说,当一定时间内没有持续触发事件时,事件处理函式才会被执行一次,但如果在设定的时间内又一次触发了事件,就会重新开始计时。
使用场景 输入框实施匹配结果
function debounce(fn,delay = 500){
let timer ;
return (...args) =>{
clearTimeout(timer);
timer = setTimeout(()=>{
fn(...args)
},delay)
}
}
function abc(){
console.log("我来执行任务了");
// 以下执行ajax 请求等逻辑处理
}
$("#watch").on("input propertychange",(e)=>{
debounce(abc(),500)
})
节流 (throttle) 指的是,在一段时间内只会执行一次触发事件的回调 (callback) 函式,若在这之中又有新事件触发,则不执行此回调函式。
使用场景 监听滚动事件
function throttle(fn,delay=500){
let timer;
return (...args)=>{
if(timer) return;
timer = setTimeout(function(){
fn(...args);
timer = null
},delay)
}
}
function getWindowHeight(){
console.log('当前滚动条的位置',$(document).scrollTop());
}
window.addEventListener("scroll",()=>{
throttle(getWindowHeight(),100)
})