【问题标题】:A throttle not calling the last throttled argument节流阀未调用最后一个节流参数
【发布时间】:2018-10-08 21:21:31
【问题描述】:

上下文:我正在写一个简单的油门,任务是javascript tutorial

任务:编写一个像这样工作的节流阀:

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 
}

【问题讨论】:

  • 谷歌debounce js。

标签: javascript throttling


【解决方案1】:

一些事情:

1) 交换 isCoolDown = false 和 isCoolDown = 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);
     }
  };
}

【讨论】:

    【解决方案2】:

    这一行有一个错误:

    f.apply(this, queue.slice(-1))
    

    .slice 方法将返回一个数组。由于args 是一个数组,queue.slice(-1) 的结果将类似于:

    [ [1, 2, 3] ]
    

    相反,您可以将其更改为:

    f.apply(this, queue.slice(-1)[0])
    

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 2021-07-02
      • 2020-01-22
      • 2017-03-22
      • 2012-05-11
      • 2019-10-03
      相关资源
      最近更新 更多