【问题标题】:Lodash the timer of debounce function doesn't work correctlyLodash debounce 功能的定时器不能正常工作
【发布时间】:2019-12-23 09:55:48
【问题描述】:

我尝试使用 lodash 的 _.debounce 函数,像这样:

var count = 0;
var debouncedFunction = _.debounce(() => console.log('debounce'), 500);
var timer = setInterval(() => {
  console.log('setInterval');
  count++;
  if (count === 505) {clearInterval(timer);}
}, 1);
debouncedFunction();

问题是:定时器计数到 127 后,去抖动功能将被触发,而我预计它应该在定时器计数到 500 后触发。
我不知道为什么对这个问题有任何想法。

【问题讨论】:

    标签: javascript jquery lodash


    【解决方案1】:

    setInterval 的时间并不完全准确。 5-10 毫秒以下的量不是很可靠。有关问题,请参阅specification

    此 API 不保证计时器将完全按计划运行。由于 CPU 负载、其他任务等导致的延迟是可以预料的。

    即使在最佳条件下,也不应该相信超时和间隔的准确度低于 10 毫秒。

    10 毫秒可以正常工作:

    // Give the browser time to finish initial load
    setTimeout(() => {
      var count = 0;
      var debouncedFunction = _.debounce(() => console.log('debounce'), 500);
      var timer = setInterval(() => {
        console.log('setInterval', count);
        count += 10;
        if (count === 510) {clearInterval(timer);}
      }, 10);
      debouncedFunction();
    }, 500);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    (对我来说,debounce 大约在记录 430 时运行)

    20 毫秒效果更好(460 或 480):

    // Give the browser time to finish initial load
    setTimeout(() => {
      var count = 0;
      var debouncedFunction = _.debounce(() => console.log('debounce'), 500);
      var timer = setInterval(() => {
        console.log('setInterval', count);
        count += 20;
        if (count === 520) {clearInterval(timer);}
      }, 20);
      debouncedFunction();
    }, 500);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    这不是 Lodash 的问题,而是超时不精确的问题。

    为了更精确的计时,经常运行一个间隔,并使用performance.now()(或者可能是Date.now())检查与间隔开始的毫秒差:

    // Give the browser time to finish initial load
    setTimeout(() => {
      const initial = performance.now();
      var debouncedFunction = _.debounce(() => console.log('debounce'), 500);
      var timer = setInterval(() => {
        const diff = performance.now() - initial;
        console.log('setInterval', diff);
        if (diff >= 520) {clearInterval(timer);}
      });
      debouncedFunction();
    }, 500);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-01
      • 2016-01-09
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2020-12-19
      • 2019-11-09
      相关资源
      最近更新 更多