码迷,mamicode.com
首页 > 其他好文 > 详细

防抖和节流

时间:2019-09-15 19:24:56      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:on()   清空   如何   throttle   概念   执行   ttl   UNC   需要   

一、概念

  1. 防抖
    • 把多个顺序的调用合并成一次,也就是在一定的时间内,规定事件被触发的次数
    • 如何实现
      // 简单的防抖函数
      function debounce(func, wait){
          var timeout;
          return function() {
              clearTimeout(timeout);      // 清除计时器
              timeout = setTimeout(func, wait);
          };
      };
      
      // 实际想要请求的函数
      function realFun(){
          console.log(success);
      }
      
      // 采用防抖
      window.addEventListener(scroll, debounce(realFun, 500));
      
      // 没有采用防抖动
      window.addEventListener(scroll, realFunc);
        
  2. 节流
    • 为什么有了防抖还不满足,出了个节流呢?因为一般我们往下滑动的时候,不停的触发scroll事件,如果只有防抖函数,那么有可能会出现空白,因为会一直的清空计时器不会发生请求。所以,我们想要一边滑动,一边出现内容,并且不会出现浏览器掉帧,这就需要节流的存在了。
    • 什么是节流?节流与防抖相比,就是保证在一定时间内至少执行一次我们希望触发的事件。
    • 实现
      // 节流函数
      function throttle(func, wait, mustRun){
          var timeout, startTime = new Date();
          return function(){
              var context = this;        // 其实这里的this指的是window
              var curTime = new Date();
              clearTimeout(timeout);
              if(curTime - startTime >= mustRun){
                  func.apply(context);
                  startTime = curTime;
              }else {
                  timeout = setTimeout(func, wait);
              }
          };
      };
      
      // 要出发的事件handler
      function realFunc(){
          console.log(success);
      }
      
      // 采用节流函数
      window.addEventListener(scroll, throttle(realFunc, 500, 1000));

       

防抖和节流

标签:on()   清空   如何   throttle   概念   执行   ttl   UNC   需要   

原文地址:https://www.cnblogs.com/pingzi-wq/p/11523619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!