JS防抖和节流的实现

防抖 

function debounce(fn, delay, option) {
  var timer = null;
  if (!option) option = {};
  leading = option.leading || false;
  result = option.result || null;
  var handleFn = function () {
    if (timer) clearTimeout(timer);
    // 获取this和argument
    var _this = this;
    var _arguments = arguments;

    if (leading) {
      // 通过一个变量来记录是否立即执行
      var isInvoke = false;
      if (!timer) {
        callFn(_this, _arguments);
        isInvoke = true;
      }
      // 定时器通过修改timer来修改instant
      timer = setTimeout(function () {
        timer = null;
        if (!isInvoke) {
          callFn(_this, _arguments);
        }
      }, delay);
    } else {
      timer = setTimeout(function () {
        // 在执行时,通过apply来使用_this和_arguments
        callFn(_this, _arguments);
      }, delay);
    }
  }

  function callFn(context, argument) {
    var res = fn.apply(context, argument);
    if (result) {
      result(res);
    }
  }

  // 取消处理
  handleFn.cancel = function () {
    if (timer) clearTimeout(timer);
  }

  return handleFn;
}

节流

function throttle(fn, interval, option) {
  var last = 0;
  var timer = null;
  if (!option) option = {};

  var trailing = option.trailing || false;
  var result = option.result || null;

  var handleFn = function() {
    // this和argument
    var _this = this;
    var _arguments = arguments;

    var now = new Date().getTime();
    if (now - last > interval) {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      callFn(_this, _arguments);
      last = now;
    } else if (timer === null && trailing) { // 只是最后一次
      timer = setTimeout(function() {
        timer = null;
        callFn(_this, _arguments);
      }, interval);
    }
  }

  handleFn.cancel = function() {
    clearTimeout(timer);
    timer = null;
  }

  function callFn(context, argument) {
    var res = fn.apply(context, argument);
    if (result) {
      result(res);
    }
  }

  return handleFn;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值