防抖动和函数节流

针对高频度触发事件问题(例如页面 scroll ,屏幕 resize,监听用户输入等)。有两种常用的解决方法,防抖和节流。

一、防抖动

        防抖就是在一段时间内如果一直触发着滚动事件,则handler函数不会触发。而是等到规定的时间段内没有监听到滚动事件再触发最后的handler函数,之前的handler函数则被清除不会触发。防抖技术即是可以把多个顺序地调用合并成一次,也就是在一定时间内,规定事件被触发的次数。

function debounce(func,wait,immediate) {
        var timeout;

        return function(){
          clearTimeout(timeout);
          timeout=setTimeout(func, wait);
        }
      }
      function realFunc() {
        console.log("success");
      }
       
      window.addEventListener('scroll', realFunc);                 //无防抖动
      window.addEventListener('scroll', debounce(realFunc,500));         //有防抖

二、函数节流

只允许一个函数在x毫秒内执行一次,只有当上一个函数执行过了规定的时间间隔,下一个函数才会被执行。

与防抖相比,节流函数最主要的不同在于它保证在 X 毫秒内至少执行一次我们希望触发的事件 handler。

与防抖相比,节流函数多了一个 mustRun 属性,代表 mustRun 毫秒内,必然会触发一次 handler ,同样是利用定时器


 function throttle(func, wait, mustRun) {
          var timeout,
              startTime = new Date();
       
          return function() {
              var context = this,
                  args = arguments,
                  curTime = new Date();
       
              clearTimeout(timeout);
              // 如果达到了规定的触发时间间隔,触发 handler
              if(curTime - startTime >= mustRun){
                  func.apply(context,args);
                  startTime = curTime;
              // 没达到触发间隔,重新设定定时器
              }else{
                  timeout = setTimeout(func, wait);
              }
          };
      };
      // 实际想绑定在 scroll 事件上的 handler
      function realFunc(){
          console.log("Success");
      }
      // 采用了节流函数
      window.addEventListener('scroll',throttle(realFunc,500,1000));
3.图片的懒加载就是利用了函数节流的思想。

猜你喜欢

转载自blog.csdn.net/qq_33745501/article/details/80658989