Menu
CoddyTech

Timer

Teil des Abschnitts Node.js-Grundlagen der Node.js-Journey von Coddy. Lektion 27 von 33.

Eine Erinnerung soll auf dem Bildschirm Schritt für Schritt herunterzählen und dann anhalten.

setInterval(fn, ms) führt fn alle ms Millisekunden aus, bis clearInterval(id) es anhält; setTimeout wird einmal ausgeführt. Ein Programm endet erst, wenn kein Timer mehr übrig ist. Ein Intervall, das du nie löschst, hält es also am Laufen.

let lap = 1;
const id = setInterval(() => {
    console.log(`Lap ${lap}`);
    lap += 1;
    if (lap > 3) {
        clearInterval(id);
    }
}, 500);

Das Terminal beendet ein Programm nach 5 Sekunden. So bemerkst du ein vergessenes clearInterval.

challenge icon

Aufgabe

Einfach

Eine Erinnerung zählt auf dem Bildschirm herunter, bevor sie die Notiz anzeigt. Füge einen Befehl remind hinzu, der dies mit einem Timer erledigt.

  1. Füge in notes.js einen Befehl remind hinzu. Das Wort danach ist eine Notiznummer, die genauso überprüft wird wie bei done. Du kannst also noteNumber wiederverwenden.
  2. Starte ein setInterval mit einer Verzögerung von 200 Millisekunden. Bei jedem Tick wird eine Zeile ausgegeben: zuerst 3, dann 2, dann 1 und schließlich der Text der Notiz.
  3. Stoppe nach der Ausgabe der Notiz das Intervall mit clearInterval, damit das Programm endet.

Mit den Notizen Buy milk und Call Ada gibt node notes.js remind 2 diese Zeilen aus, jeweils eine alle 200 Millisekunden:

3
2
1
Call Ada
  1. Eine Zahl, die keiner Notiz entspricht, führt zum selben Fehler wie bei done. Bei zwei Notizen gibt node notes.js remind 9 No note 9 auf stderr aus und beendet das Programm mit Code 1, ohne herunterzuzählen.

Probiere es aus: Gib remind 1 in das Feld nach $ node notes.js ein und drücke die Eingabetaste. Du siehst den Countdown und danach deine erste Notiz. Gib dann remind 9 ein: Du siehst No note 9 in Rot und den Exit-Code 1. Wenn du clearInterval vergisst, endet das Programm nicht von selbst und das Terminal stoppt es nach 5 Sekunden.

Probier es selbst

// Dein Notiztool beginnt hier.
import { rmSync } from 'node:fs';
import path from 'node:path';
import { formatNote } from './format.js';
import stats from './legacy/stats.cjs';
import store from './store.js';

const [command, ...words] = process.argv.slice(2);
const text = words.join(' ');

const noteNumber = (word) => {
    const n = Number(word);
    if (!Number.isInteger(n) || n < 1 || n > store.notes.length) {
        console.error(`No note ${word}`);
        process.exit(1);
    }
    return n;
};

if (command === 'add') {
    const n = await store.add(text);
    console.log(`Saved note ${n}.`);
} else if (command === 'list') {
    const owner = process.env.NOTES_OWNER ?? 'you';
    console.log(`Notes for ${owner}`);
    if (store.notes.length === 0) {
        console.log('No notes yet');
    }
    const lines = store.notes.map((note, i) => formatNote(i + 1, note));
    if (store.settings.sort === 'newest') {
        lines.reverse();
    }
    lines.forEach((line) => console.log(line));
} else if (command === 'where') {
    const file = path.join(process.cwd(), 'notes.json');
    console.log(file);
    console.log(path.basename(file));
} else if (command === 'stats') {
    console.log(`${store.notes.length} notes, ${stats.countWords(store.notes)} words`);
} else if (command === 'done') {
    const removed = await store.remove(noteNumber(words[0]));
    console.log(`Done: ${removed}`);
} else if (command === 'clear') {
    rmSync('notes.json', { force: true });
    console.log('Deleted notes.json');
} else {
    if (command) {
        console.error(`Unknown command: ${command}`);
    }
    console.error('Usage: node notes.js <command> [words]');
    process.exit(1);
}

Alle Lektionen in Node.js-Grundlagen

Übe selbstständig: Express-Playground