Adie trabalho com setTimeout2() e clearTimeout2()
setTimeout2(id, callback, timeout) é setTimeout com um nome. Quando o chama de novo com o mesmo id antes de o tempo acabar, o temporizador anterior é cancelado e substituído: o callback executa-se uma vez, depois de as chamadas deixarem de chegar. É a forma habitual de guardar, recarregar ou recalcular uma só vez quando muitos eventos chegam juntos (uma rajada de alterações, a escrita, uma enxurrada de mensagens).
clearTimeout2(id) cancela o temporizador desse id e devolve true quando havia um e false quando não havia.
A forma completa é setTimeout2(id, callback, timeout, limit, a, b, c, d, e): os valores depois de limit são passados ao callback. Não use limit em total5 0.0.19: a ideia é executar o callback de imediato após limit substituições, mas o contador nunca arranca (é undefined e passa a NaN), pelo que o callback só é chamado quando o tempo acaba. O exemplo chama-o dez vezes com um limite de 3 e o callback não correu antes do tempo.
exports.install = function() {
ROUTE('GET /burst/', burst);
};
async function burst($) {
const log = [];
// three calls with the same id: only the last one runs
setTimeout2('save', () => log.push('first'), 100);
setTimeout2('save', () => log.push('second'), 100);
setTimeout2('save', () => log.push('third'), 100);
// a timer that is cancelled before it runs
setTimeout2('gone', () => log.push('gone'), 100);
const cancelled = clearTimeout2('gone');
const nothing = clearTimeout2('never-set');
// the values after the limit reach the callback
setTimeout2('args', (a, b) => log.push(a + b), 50, 0, 'x', 'y');
// the limit option does not run the callback early
let early = 0;
for (let i = 0; i < 10; i++)
setTimeout2('limited', () => early++, 1000, 3);
const stopped = clearTimeout2('limited');
await new Promise(resolve => setTimeout(resolve, 300));
$.json({ log: log, cancelled: cancelled, nothing: nothing, early: early, stopped: stopped });
}