Javascript 返回倍数的去盎司函数

Javascript 返回倍数的去盎司函数,javascript,function,debounce,Javascript,Function,Debounce,上下文:这是我第一次尝试实现一个debounce()函数,可能我误解了什么,因为函数多次调用我的API,尽管延迟已经应用,但我的代码: async updateSelectAll(value) { const execute = this.debounce(async () => { await this.getTotalDaeMunicipio(this.filtroDaeMunicipio); await this.gerarGraficoMunicipio();

上下文:这是我第一次尝试实现一个
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)后,通过函数
execute()
调用API,该函数具有
debounce
功能,但当用户多次单击复选框时,API被多次调用


预期行为:当多次单击checkobox时,它意味着只对API执行一次调用。

您在debounce函数中创建一个局部变量
timer
,内部函数关闭并访问该变量

debounce(func, wait) {
  let timer = null;
  return () => {
    clearTimeout(timer);
    timer = setTimeout(func, wait);
  };
}

但问题是,您多次调用了
this.debounce()
,而这并不共享此
计时器。您需要在每次调用debounce时共享此计时器,以实现您的目标

使用可观测值!我认为问题在于如何声明计时器变量。尝试将其声明出debounce函数范围,它已工作!我将
定时器
变量放入Vue的
数据
,并删除
this.timer=null
并工作!谢谢你D