前端于我
记录 / js / 优化

节流防抖的简单实现

节流的简单实现

function throttle(fn, time) {
  var lock = false;
  return function() {
    if (lock) return;
    lock = true;
    try {
      fn.apply(this, arguments); // 需要注意this和参数需要带上
    } catch(err) {} finally {
      setTimeout(function() { // 为了防止方法执行有错误导致节流锁死,用finally保证锁不被锁死
        lock = false;
      }, time);
    }
  };
}

防抖的简单实现

function debounce(fn, time) {
  var timeoutKey;
  return function() {
    if (timeoutKey) {
      clearTimeout(timeoutKey);
    }
    var _this = this;
    var args = arguments;
    timeoutKey = setTimeout(function() {
      timeoutKey = undefined;
      fn.apply(_this, args);
    }, time);
  }
}
发表于: 2020-07-30