gpt4 book ai didi

javascript - 去抖功能多次返回

转载 作者:行者123 更新时间:2023-11-30 13:46:45 24 4
gpt4 key购买 nike

上下文: 这是我第一次尝试实现 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com