js防抖和节流

88 阅读1分钟

防抖:只执行最后一次;

应用场景:搜索;文本框搜索

function debounce(fun,wait){
let timeId = null;

return function(...args){
    if(timeId !== null){
        clearTimeout(timeId);
    }
    
    timeId = setTimeout(()=>{
        fun.apply(this,args);
    },wait);
};

}

function search() {
  console.log('searching...');
  // 发送请求获取搜索结果
}

const debounce1 = debounce(search, 500);
debounce1()
debounce1()


节流:在一段时间执行一次;

应用场景:快速点击;鼠标滑动;resize;scroll滑动;下拉加载;视频播放记录时间等;

function throttle(event, wait) { 
    let timer = null; 
    return function (...args) 
        { 
            if (!timer) {
                timer = setTimeout(() => { 
                timer = null; 
                event.apply(this, args)
            }, wait) 
            }
        }
}






// 调用参考
const throttleFun = throttle((arg) => {console.log(arg)}, 1000);
throttleFun(1) // 1
throttleFun(1)