防抖与节流

  • 防抖与节流的本质就是:通过闭包特性减少操作次数

  • 举一个现实生活中的例子

 // 两个大巴的故事
 // 防抖,
 // A大巴:车上上去一个人,五分钟之内不上人,发车。
 // 节流。
 // B大巴:车上上去一个人之后,五分钟之后发车。

 // 发车!网络请求(A => B) 提高利用率 减少B的压力。

 // 防抖:举个例子 从第一个字母开始,.5s 没有文字输入,发送请求。 
       // fn 具有防抖函数,wait 时间间隔, 返回的函数,跟fn具有同样的功能,具有防抖的特性,更多应用场景 鼠标移动,滚动条。
       function debounce(fn, wait) {
           let timer = null;
           return function (...arg) {
               clearTimeout(timer);
               timer = setTimeout(() => {
                   fn(...arg);
               }, wait);
           }
       }

       var input = document.getElementById('inp');
       function ajax (e) {
           console.log('发送数据'+ e.target.value);
       }
       input.oninput = debounce(ajax, 500)
  
   // 节流。
     // fn要执行,等待wait时间后在执行fn
     function throttle(fn, wait) {
            let timer = null;
           // 返回函数执行:车上人
           return (...arg) => {
               // 如果没有开启定时器,开启一个
               if (!timer) {
                   // 到时间发车
                   timer = setTimeout(function () {
                       fn(...arg);
                       timer = null;
                   }, wait); 
               }
           }
       }

       var _ajax = throttle(ajax, 2000);
       input.oninput = _ajax
posted @ 2024-02-13 18:46  HuangBingQuan  阅读(11)  评论(0编辑  收藏  举报