简体   繁体   English

从setInterval调用时,Lodash的反跳功能不起作用

[英]Lodash debounce doesn't work when called from setInterval

I'm trying to call a debounced function from setInterval but for some reason it doesn't works and the function doesn't invoke, any idea why? 我正在尝试从setInterval调用一个去抖动的函数,但是由于某种原因,该函数不起作用,并且该函数无法调用,为什么?

const _ = require('lodash');

const debouncedFunction = _.debounce(() => console.log('test'), 4000);

setInterval(() => {
    console.log('tick');
    debouncedFunction();
}, 1000);

It is worth to mention that if I replace the setInterval with setTimeout it works 值得一提的是,如果我将setInterval替换为setTimeout,那么它将起作用

https://repl.it/@ShahafMango/CheeryKaleidoscopicOffice https://repl.it/@ShahafMango/CheeryKaleidoscopicOffice

The purpose of wrapping a function with debounce is to delay the execution of the function as long as it's called repeatedly. 使用反跳功能包装函数的目的是,只要重复调用该函数,就可以延迟该函数的执行。 The wait parameter states the time that should elapse after the last call of the debounced function, before the inner function is invoked. wait参数表示在最后一次调用去抖动功能之后,在调用内部功能之前应该经过的时间。 If the the interval calls the function once every 1000ms, and the wait is 4000ms, the wrapped function would never be called. 如果间隔每1000ms调用一次函数,并且等待时间为4000ms,则包装函数将永远不会被调用。

Changing the interval to something less than 1000 will call the function (and probably defeat the original purpose of wrapping with debounce): 将时间间隔更改为小于1000的值将调用该函数(并可能破坏了用去抖动包装的初衷):

 const debouncedFunction = _.debounce(() => console.log('test'), 500); setInterval(() => { console.log('tick'); debouncedFunction(); }, 1000); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script> 

If you want to limit the function to work once every 4000ms use _.throttle() instead. 如果要限制该功能每4000 _.throttle()工作一次,请使用_.throttle() Throttle will limit the invocation of the inner function to once per the wait time, no matter how many times the wrapped function was called. 节流将把内部函数的调用限制为每个等待时间一次,无论包装函数被调用了多少次。

 const debouncedFunction = _.throttle(() => console.log('test'), 4000); setInterval(() => { console.log('tick'); debouncedFunction(); }, 1000); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM