Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
Solo ejecuta una función una vez en un período de tiempo determinado

Tengo una solicitud de API que se llama varias veces en un período de tiempo determinado. Más específicamente, esta solicitud es para actualizar el token de usuario, por lo que se llama en cada solicitud, lo que se suma bastante rápido. Me gustaría crear una función que le diga a la función que no se ejecute durante una cantidad determinada de segundos. He intentado usar lodash debounce pero no puedo hacerlo funcionar.

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

¿Estoy ejecutando esto mal? Es posible de hacer?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Sí, definitivamente necesitas throttle para el trabajo.

 // 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>

Fragmento de github

about 4 years ago · Juan Pablo Isaza Report

0

¿Has probado con un tiempo de espera?

 const myTimeout = setTimeout(debounceRefresh, 1000);

Si se vuelve a llamar a la función, puede borrar el tiempo de espera y restablecerlo

clearTimeout(myTimeout);

¿Por qué no usas un oyente diferente? ¿Quizás cuando se reciben los datos?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!