美文网首页
每日一条JS精华片段:创建一个受限制的函数

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

作者: _夏之_ | 来源:发表于2020-09-07 20:57 被阅读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记录一次窗口尺寸

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

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/bczlektx.html