Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
Only execute a function once in a given amount of time

I have an api request that is called multiple times in a given amount of time. More specifically this request is for refreshing the user token, so it's called on every request, which adds up pretty quickly. I would like to create a function that tells the function not to run for a given amount of seconds. I have tried using lodash debounce but I can't get it to work.

let debounceRefresh;

debounceRefresh = debounce(() => {
  api.request(){
  });
}, 1000);

debounceRefresh();

Am I executing this wrong? Is it possible to do?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Yes, you definitely need throttle for the job.

// in this example we invoke a fn for a period of 10 sec, invoking it 2 times a second, but we can perceive that the original function is only invoked at most once per 2 seconds according to the parameter below:

var TOTAL_TIME_TO_RUN = 10000; // 10 sec
var THROTTLE_INTERVAL = 2000; // <= adjust this number to see throttling in action
var INVOCATION_INTERVAL = 500; // 0.5 sec

// regular fn
var punchClock = function punchClock() {
  console.log(new Date().toISOString() + ' - call api');
};

// wrap it and supply interval representing minimum delay between invocations
var throttledPunchClock = _.throttle(punchClock, THROTTLE_INTERVAL);

// set up looping
var intervalId = setInterval(function() {
  console.log("attempting call api");
  throttledPunchClock()
}, INVOCATION_INTERVAL);

// run the demo
setTimeout(() => clearInterval(intervalId), 10000)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<pre>
  var TOTAL_TIME_TO_RUN = 10000; // 10 sec
  var THROTTLE_INTERVAL = 2000; // < = adjust this number to see throttling in action
  var INVOCATION_INTERVAL = 500; // 0.5 sec
</pre>

Snippet from github

about 4 years ago · Juan Pablo Isaza Relatório

0

Have you tried with a timeout?

const myTimeout = setTimeout(debounceRefresh, 1000);

If the function is called again, you can clear the timeout and reset it

clearTimeout(myTimeout);

Why don't you use a different listener? Perhaps when data is received?

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda