JS中的防抖和节流

防抖

较为常见的应用场景就是输入框输入完成后再去查询数据,避免输入一次向服务端发送请求查询一次。

class Debounce {
  constructor(fn, timeOut) {
    this.timer = null;
    return (...args) => {
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        fn.call(this, ...args);
      }, timeOut);
    };
  }
}
<input type="text" id="input" oninput="input()" />
 <script>
      var dom = document.getElementById('input');
      function query() {
        console.log(arguments);
      }
      var debounce = new Debounce(query, 300); //  设置防抖时间为300ms
      function input(e) {
        debounce(dom.value);
      }
 </script>

效果如下
请添加图片描述

节流

应用场景就是当一些操作触发事件的频率非常高,我们可以用节流来实现在规定时间内只执行一次。这也算是一些优化的小技巧吧
class Throttle {
  constructor(fn, delay) {
    this.lastTime = 0;
    return (...args) => {
      var currentTime = new Date().getTime();
      if (currentTime - this.lastTime >= delay) {
        fn.apply(this, args);
        this.lastTime = currentTime;
      }
    };
  }
}
function _throttle(...data) {
        console.log(data);
}
var throttle = new Throttle(_throttle, 0);//  未设置节流时间!

window.onresize = throttle.bind(throttle, 123);

请添加图片描述
可以看到不使用节流的话这一会执行了一百多次这个函数

这里设置节流时间为一秒钟
var throttle = new Throttle(_throttle, 1000)

可以看到效果还是挺明显的
请添加图片描述

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值