websocket之性能优化-防抖函数

在用户执行某种特定操作时(频率很高),我们没必要每次都监听这个函数,如淘宝搜索栏,百度搜索栏快速输入值检索过滤,可以定义多少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))

版权声明:本文为weixin_39531576原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。