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?
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
¿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?