如何对 Angular 中的方法进行去抖动
How to debounce a method in Angular
我有一个方法调用 foo()
正在调用 API,foo()
方法在滑块 eventChange
方法内部调用,滑块有一个步长为 100,而 maxNum
为 500k+,因此当有人滑动滑块时,它将调用 eventChange
方法超过 1 次。
现在我想在进行 API 调用之前将方法 foo()
去抖动 400 毫秒,就像我们在 FormControl
值更改时所做的那样。
我尝试过使用 lodash 去抖
var debounce = _.debounce(function(){
foo();
}, 30000);
debounce();
但它说 foo()
不是函数。如何使用原始 TypeScript 对方法 foo()
去抖动。
注意。 Foo() 无法绑定到任何 html.
好吧,我设法通过 setTimeout
解决了这个问题,作为去抖动器,它非常适合我,
onSliderEventChanges(event:ChangeContext){
if(this.timerid !== null){
clearTimeout(this.timerid);
}
this.timerid = setTimeout(() =>
{
this.foo(false);
this.timerid = null;
}, 400);
}
第一个 if 将始终清除最后一个 运行 timeOut
,因此滑动结束时我将只调用一次 foo()
因为只有最后一个 timeOut
还活着。
setTimeout
总是return一个timerId
.
您可以使用 lodash-decorators 轻松地将 lodash 操作应用于函数
@debounce(1000)
foo() { ... }
它对 angular 全部基于 class 的组件或服务特别有用。
我有一个方法调用 foo()
正在调用 API,foo()
方法在滑块 eventChange
方法内部调用,滑块有一个步长为 100,而 maxNum
为 500k+,因此当有人滑动滑块时,它将调用 eventChange
方法超过 1 次。
现在我想在进行 API 调用之前将方法 foo()
去抖动 400 毫秒,就像我们在 FormControl
值更改时所做的那样。
我尝试过使用 lodash 去抖
var debounce = _.debounce(function(){
foo();
}, 30000);
debounce();
但它说 foo()
不是函数。如何使用原始 TypeScript 对方法 foo()
去抖动。
注意。 Foo() 无法绑定到任何 html.
好吧,我设法通过 setTimeout
解决了这个问题,作为去抖动器,它非常适合我,
onSliderEventChanges(event:ChangeContext){
if(this.timerid !== null){
clearTimeout(this.timerid);
}
this.timerid = setTimeout(() =>
{
this.foo(false);
this.timerid = null;
}, 400);
}
第一个 if 将始终清除最后一个 运行 timeOut
,因此滑动结束时我将只调用一次 foo()
因为只有最后一个 timeOut
还活着。
setTimeout
总是return一个timerId
.
您可以使用 lodash-decorators 轻松地将 lodash 操作应用于函数
@debounce(1000)
foo() { ... }
它对 angular 全部基于 class 的组件或服务特别有用。