每日一条JS精华片段:创建一个受限制的函数

2020-09-07  本文已影响0人  _夏之_

创建一个受限制的函数,每wait毫秒最多只能调用一次

Javascript方法

const throttle = (fn, wait) => {
  let inThrottle, lastFn, lastTime;
  return function() {
    const context = this,
      args = arguments;
    if (!inThrottle) {
      fn.apply(context, args);
      lastTime = Date.now();
      inThrottle = true;
    } else {
      clearTimeout(lastFn);
      lastFn = setTimeout(function() {
        if (Date.now() - lastTime >= wait) {
          fn.apply(context, args);
          lastTime = Date.now();
        }
      }, Math.max(wait - (Date.now() - lastTime), 0));
    }
  };
};

示例

window.addEventListener(
  'resize',
  throttle(function(evt) {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
  }, 250)
);

执行结果

最多就250ms记录一次窗口尺寸

请关注我,每天获得一条精华小片段!

上一篇 下一篇

猜你喜欢

热点阅读