Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda