首页 > 其他 > 详细

防抖和节流函数

时间:2019-11-20 20:00:16      阅读:94      评论:0      收藏:0      [点我收藏+]

防抖函数解决的问题:

防止误操作等多次输出点击等事件造成的多次通信请求。


防抖代码如下:

const debounce = (fn, delay = 1000) => {
  let timer = null;
  return (...args) => {
    console.log(`clear timer:`, this.timer);  //必须要写this.
    console.log(`_that===this :`, _that === this);
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
    console.log(`timer value:`, this.timer);
  };
};

html占用调用

 <button onclick="debounce(clickFun)()">防抖点击</button>
function clickFun(){
alert(''点击");
}


节流函数解决的问题:

当dom布局频繁Resize时需要使用节流函数减少回流或重绘的次数。

节流函数代码如下:

 const throttle=(fn,delay=1000)=>{
      let flag=false;
      return (...args)=>{
        if(this.flag)return;
          this.flag=true;
          setTimeout(() => {
            fn.apply(this,args);
            this.flag=false;
          }, delay);
      }
    }

html中调用:

 <button onclick="throttle(clickFun)()">节流点击</button>
function clickFun(){
alert(''点击");
}

TODO:下次将写一篇关于前端性能优化的文章(三方面:通讯优化、首屏渲染优化、界面操作性能优化)

防抖和节流函数

原文:https://www.cnblogs.com/M-Silencer/p/11899808.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!