Ir para o conteúdo

CódigoNão tentada

Throttle (leading + trailing)

Dificuldade: média

Deixe fn executar no máximo uma vez a cada wait ms, como o padrão do lodash.

  • a primeira chamada executa imediatamente (leading)
  • as chamadas durante a janela se juntam; quando a janela termina, fn executa mais uma vez com os argumentos mais recentes (trailing), o que abre uma nova janela
  • se nada foi chamado durante a janela, nada executa no fim dela

Pergunta extra: quando você escolheria throttle em vez de debounce? (posição de scroll vs campo de busca)

Ver solução de referência
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);
};
}
Carregando editor…