前端性能优化-防抖和节流

前端性能优化-防抖和节流

防抖和节流是什么
  • 防抖
    让函数在停止触发事件后的一段时间再执行
  • 节流
    让函数以固定的频率触发
为什么要防抖节流

当我们给一个按钮,或者鼠标的移动添加相应事件的时候,如果不需要实时响应,就可以使用防抖,节流来优化页面的性能
html

     <button id="add">点击加一</button>
     <label id="addLable" for="add"></label>

js

let count = 0;
const add = document.querySelector('#add');
const addLabel = document.querySelector('#addLable');
add.addEventListener('click', () => {
  addLable.innerHTML = ++count;
});

在这里插入图片描述

防抖

防抖的原理就是让函数让函数延时执行,如果期间触发了新事件,则取消原来的延时计划
html

 <button id="add1">防抖加一</button>
 <label id="addLable1" for="add1"></label>

js

let count1 = 0;
const add1 = document.querySelector('#add1');
const addLabel1 = document.querySelector('#addLable1');
let timeout;
const add1Click = function() {
 addLabel1.innerHTML = ++count1;
};
add1.addEventListener('click', () => {
 if (timeout) {
   clearTimeout(timeout);
 }
 timeout = setTimeout(add1Click, 500);
});

在这里插入图片描述
更优雅的代码
知道了原理后,就可以用lodash工具库帮我们实现啦,看着更方便简洁
_.debounce(func,timeout)
lodash官网

let count1 = 0;
const add1 = document.querySelector('#add1');
const addLabel1 = document.querySelector('#addLable1');
let timeout;
const add1Click = function() {
  addLabel1.innerHTML = ++count1;
};
// add1.addEventListener('click', () => {
//   if (timeout) {
//     clearTimeout(timeout);
//   }
//   timeout = setTimeout(add2Click, 500);
// });
add1.addEventListener('click', _.debounce(add1Click, 500));
节流

节流函数在一定时间内,只触发一次
html

      <button id="add2">节流加一</button>
      <label id="addLable2" for="add2"></label>

js

let count2 = 0;
const add2 = document.querySelector('#add2');
const addLabel2 = document.querySelector('#addLable2');
const add2Click = function() {
  addLabel2.innerHTML = ++count2;
};
let beAbleClick = true;
add2.addEventListener('click', () => {
  if (!beAbleClick) {
    return;
  }
  setTimeout(() => {
    add2Click();
    beAbleClick = true;
  }, 500);
  beAbleClick = false;
});

在这里插入图片描述
更优雅的代码
同样lodash工具也有可用的方法 _.throttle(func,timeout)

let count2 = 0;
const add2 = document.querySelector('#add2');
const addLabel2 = document.querySelector('#addLable2');
const add2Click = function() {
  addLabel2.innerHTML = ++count2;
};
// let beAbleClick = true;
// add2.addEventListener('click', () => {
//   if (!beAbleClick) {
//     return;
//   }
//   setTimeout(() => {
//     add2Click();
//     beAbleClick = true;
//   }, 500);
//   beAbleClick = false;
// });
add2.addEventListener('click', _.throttle(add2Click, 500));
``
发布了83 篇原创文章 · 获赞 21 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/JsongNeu/article/details/98318685