javascript - throttle 不调用最后一个 throttle 参数

标签 javascript throttling

上下文:我正在 javascript tutorial 的任务下编写一个简单的 throttle 。

任务:编写一个像这样工作的 throttle :

function f(a) {
  console.log(a)
};

// f1000 passes calls to f at maximum once per 1000 ms
let f1000 = throttle(f, 1000);

f1000(1); // shows 1
f1000(2); // (throttling, 1000ms not out yet)
f1000(3); // (throttling, 1000ms not out yet)

// when 1000 ms time out...
// ...outputs 3, intermediate value 2 was ignored
// P.S. Arguments and the context this passed to f1000 should be passed to the original f.

这是我的解决方案。奇怪的是,当我在调试控制台中逐步运行它时,它工作正常,但在其他情况下则不然。知道为什么以及如何解决它吗? (我认为它与setTimeout有关?)

function throttle(f, ms) {
  let isCoolDown = true,
  queue = []

  function wrapper(...args) {
    queue.push(args)

    if (!isCoolDown) return

    isCoolDown = false
    setTimeout(function() {
      isCoolDown = true
      if (queue[0] !== undefined) {
        f.apply(this, queue.slice(-1))
        queue = []
      }
    }, ms)

    return function() {
      f.apply(this, args)
      queue = []
    }()
  }
  return wrapper 
}

最佳答案

一些事情:

1) 交换 isCoolDown = falseisCoolDown = true

2)您不需要队列,只有一个调用必须经过其他调用,其他调用会因限制而被丢弃

<小时/>
 function throttle(fn, ms) {
   let throttle = false;
   let timer;

   return wrapper(...args) {
     if(!throttle) { // first call gets through
        fn.apply(this, args);
        throttle = true;
     } else { // all the others get throttled
        if(timer) clearTimeout(timer); // cancel #2
        timer = setTimeout(() => {
          fn.apply(this, args);
          timer = throttle = false;
        }, ms);
     }
  };
}

关于javascript - throttle 不调用最后一个 throttle 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52576307/

相关文章:

javascript - 如何使用 jQuery 选择在 <text> 中具有特定文本的特定 <g> 作为其子级?

javascript - 关于基思·伍德倒计时器

bash - 使用 throttle 将文件通过管道传输到标准输入

jquery - 如何使用 underscore.js 中的 throttle

javascript - 处理从对象数组中抓取对象的更好方法?

javascript - 每 3 个月和 6 个月在 later.js 上重复一次,从特定日期开始说明

javascript - 显示图像,该图像在作为服务器运行时在类型文件中输入,但未在浏览器中显示

javascript - window.onresize : firing a function during, 以及调整大小完成时

linux - 基于协议(protocol)(UDP、TCP 等)在 Linux 上模拟丢包

javascript - 将 Throttle-Debounce 与 addEventListener 结合使用