作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
上下文: 这是我第一次尝试实现 debounce()
函数,可能我误解了一些东西,因为该函数多次调用我的 API,尽管延迟它被应用,我的代码:
async updateSelectAll(value) {
const execute = this.debounce(async () => {
await this.getTotalDaeMunicipio(this.filtroDaeMunicipio);
await this.gerarGraficoMunicipio();
}, 1000);
execute();
},
debounce(func, wait) {
let timer = null;
return () => {
clearTimeout(timer);
timer = setTimeout(func, wait);
};
}
函数 updateSelectAll
每次用户单击复选框时都会调用它,这是有效的。
问题:当用户点击复选框时,函数updateSelectAll
被调用,1秒(1000ms)后,通过函数调用API >execute()
具有debounce
功能,但当用户多次点击复选框时,该API 会被调用多次。
预期行为:当多次点击复选框时,本应只调用一次 API。
最佳答案
您在 debounce 函数中创建一个局部变量 timer
,内部函数关闭并有权访问该变量。
debounce(func, wait) {
let timer = null;
return () => {
clearTimeout(timer);
timer = setTimeout(func, wait);
};
}
但问题是,您多次调用 this.debounce()
,这并没有共享此 timer
。您需要在 debounce 调用之间共享此计时器以实现您的目标
关于javascript - 去抖功能多次返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59158401/
我是一名优秀的程序员,十分优秀!