防抖与节流

防抖 debounce

函数防抖就是在函数需要频繁触发的情况下,只有足够的空闲时间,才执行一次。

典型应用

  • 百度搜索框在输入稍有停顿时才更新推荐热词。
  • 拖拽
function debounce(handler, delay) {
  delay = delay || 300;
  var timer = null;

  return function () {
    var _self = this,
      _args = arguments;

    clearTimeout(timer);
    timer = setTimeout(function () {
      handler.apply(_self, _args);
    }, delay);
  };
}

防抖函数为什么要记录this和参数的例子: debounce-demo.js

节流 throttle

一个函数只有在大于执行周期时才执行,周期内调用不执行。好像水滴积攒到一定程度才会触发一次下落一样。

典型应用:

  • 抢券时疯狂点击,既要限制次数,又要保证先点先发出请求
  • 窗口调整
  • 页面滚动
function throttle(handler, wait) {
  wait = wait || 300;
  var lastTime = 0;

  return function () {
    var _self = this,
      _args = arguments;

    var nowTime = new Date().getTime();
    if (nowTime - lastTime > wait) {
      handler.apply(_self, _args);
      lastTime = nowTime;
    }
  };
}

复杂但好用版:

function throttle(fn, interval, context, firstTime) {
  let timer;
  firstTime = typeof firstTime !== "undefined" ? firstTime : true;
  return function () {
    let args = arguments;
    let __me = this;
    if (typeof context !== "undefined") {
      __me = context;
    }

    if (firstTime) {
      fn.apply(__me, args);
      return (firstTime = false);
    }

    if (timer) {
      return false;
    }

    timer = setTimeout(function () {
      clearTimeout(timer);
      timer = null;

      fn.apply(__me, args);
    }, interval);
  };
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值