我正在尝试在 Angular 5 项目中使用 lodash throttle 和去抖功能,但它似乎没有按预期工作。
行为是永远不会执行传递给任一函数的函数参数。
例如 throttle ,我使用以下方法导入它:
import throttle = require('lodash/throttle');
然后,在任何方法中,我都有以下内容:
throttle(this.testFunction, 100);
我也试过:
throttle(() => {
this.testFunction();
}, 1000);
testFunction 就是以下内容:
public testFunction() {
console.log('test function!@!!@!');
}
感谢任何帮助!
最佳答案
throttle
不调用函数。它返回一个新函数,该函数在被调用时确保您传递给 throttle
的真实函数被调用,最多每 x 次调用一次:
所以,如果你这样做:
throttle(func, 100);
没有任何反应。你必须这样做:
let throttledFunc = throttle(func, 100);
并且您必须调用 throttledFunc
而不是 func
。 throttledFunc
将检查您是否在至少 100 毫秒内未调用该函数
所以,如果你这样做:
setInterval(throttledFunc, 50); // execute every 50 ms.
func
只会每 100 毫秒调用一次,而不是每 50 毫秒调用一次。
关于javascript - lodash throttle nor debounce 在 Angular 5 项目中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49875995/