Saltar al contenido

CódigoSin intentar

Throttle (al inicio y al final del intervalo)

Dificultad: media

Haz que fn se ejecute como mucho una vez cada wait ms, como el comportamiento por defecto de lodash.

  • la primera llamada se ejecuta de inmediato (leading)
  • las llamadas durante la ventana se agrupan; cuando la ventana termina, fn se ejecuta una vez más con los últimos argumentos (trailing), lo que abre una ventana nueva
  • si no hubo llamadas durante la ventana, no se ejecuta nada al final

Para profundizar: ¿cuándo elegirías throttle en vez de debounce? (posición de scroll frente a un buscador)

Ver solución de referencia
export function throttle<A extends unknown[]>(fn: (...args: A) => void, wait: number): (...args: A) => void {
let timer: ReturnType<typeof setTimeout> | undefined;
let lastArgs: A | undefined; // the latest call made while waiting
let lastThis: unknown;
function endWindow() {
if (lastArgs) {
// Run the trailing call, which starts a new window.
fn.apply(lastThis, lastArgs);
lastArgs = undefined;
timer = setTimeout(endWindow, wait);
} else {
timer = undefined;
}
}
return function (this: unknown, ...args: A) {
if (timer) {
lastArgs = args;
lastThis = this;
return;
}
fn.apply(this, args); // leading call
timer = setTimeout(endWindow, wait);
};
}
Cargando editor…