Arbeit mit setTimeout2() und clearTimeout2() entprellen
setTimeout2(id, callback, timeout) ist setTimeout mit einem Namen. Rufst du es vor Ablauf der Zeit erneut mit derselben ID auf, wird der vorherige Timer abgebrochen und ersetzt: Der Callback läuft einmal, nachdem die Aufrufe aufgehört haben. Das ist der übliche Weg, nur einmal zu speichern, neu zu laden oder neu zu berechnen, wenn viele Ereignisse gemeinsam eintreffen (eine Serie von Änderungen, Tippen, eine Flut von Nachrichten).
clearTimeout2(id) bricht den Timer dieser ID ab und gibt true zurück, wenn es einen gab, und false, wenn nicht.
Die vollständige Form ist setTimeout2(id, callback, timeout, limit, a, b, c, d, e): Die Werte nach limit werden an den Callback übergeben. Verwende limit nicht in total5 0.0.19: Die Idee ist, den Callback sofort nach limit Ersetzungen auszuführen, aber der Zähler startet nie (er ist undefined und wird zu NaN), sodass der Callback erst aufgerufen wird, wenn die Zeit abgelaufen ist. Das Beispiel ruft ihn zehnmal mit einem Limit von 3 auf, und der Callback lief nicht vorzeitig.
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 });
}