Mocking function returning several times

Asked

Viewed 26 times

1

Context: It’s the first time I’ve tried to implement a function debounce() in Javascript and I think I’m forgetting or getting something wrong, because she is making several calls in the API, despite applying the delay, I have the following code:

async atualizarSelecionarTodosMunicipios(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 atualizarSelecionarTodosMunicipios(value) is called always the user clicks on a checkbox, this is working, every time I click on the checkbox this function is being called.

The problem: by clicking on the checkbox, the function atualizarSelecionarTodosMunicipios(value) is called, after 1 second (1000ms), the call is made in the API by the function execute() who owns the debounce, only that by clicking several times on the checkbox, several calls are made in the API.

What was expected: when clicking several times on the checkbox, it was to make only one call in the API.

Does anyone have any idea what I’m doing wrong? Thanks!

1 answer

1

I received a reply at Stackoverflow in English that helped me in the problem.

Answer: the problem was that the variable timer needs to be shared between functions and not be in the local scope of the function debounce, because by calling this function several times, multiple were created timer.

Up-to-date and working code:

data() {
  return {
    timer: null,
  }
}

async atualizarSelecionarTodosMunicipios(value) {
  const execute = this.debounce(async () => {
    await this.getTotalDaeMunicipio(this.filtroDaeMunicipio);
    await this.gerarGraficoMunicipio();
  }, 1000);
  execute();
},

debounce(func, wait) {
  return () => {
    clearTimeout(this.timer);
    this.timer = setTimeout(func, wait);
  };
},

Question on Stackoverflow in English

Browser other questions tagged

You are not signed in. Login or sign up in order to post.