1

Context: It's the first time I try to implement a debounce() function and probably I misunderstood something, because the function it's calling my API multiple times, although the delay it's been aplied, my code:

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);
  };
}

The function updateSelectAll it's called everytime the user clicks on a checkbox, this is working.

The problem: when the user clicks on the checkbox, the function updateSelectAll it's called, after 1 second(1000ms), the API is called through the function execute() which have the debounce function, but when the user click multiple times on the checkbox, the API is called multiple times.

Expected behavior: when the checkobox it's clicked multiple times, was meant to do just one call to the API.

2
  • Use observables! Dec 3, 2019 at 13:42
  • I think the problem is where you declare the timer variables. Try declare it out of the debounce function scope Dec 3, 2019 at 13:45

1 Answer 1

2

You create a local variable timer in the debounce function that the inner function closes over and has access to.

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

The problem is, though, that you invoke this.debounce() multiple times, which is not sharing this timer. You need to share this timer between invocations of debounce to achieve your goal

1
  • It's worked! I put the timer variable in the data of Vue and delete the this.timer = null and worked! Thanks man! :D Dec 3, 2019 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.