Menu
CoddyTech

טיימרים

חלק מהיחידה יסודות Node.js במסלול ה-Node.js של Coddy. שיעור 19 מתוך 24.

תזכורת צריכה לספור לאחור על המסך, צעד אחד בכל פעם, ואז לעצור.

setInterval(fn, ms) מפעילה את fn כל ms אלפיות שנייה, עד ש־clearInterval(id) עוצרת אותה; setTimeout מופעלת פעם אחת. תוכנית מסתיימת רק כשלא נותרו טיימרים, ולכן מרווח זמן שלא ביטלת ממשיך להפעיל אותה.

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

המסוף עוצר תוכנית אחרי 5 שניות, וכך אפשר להבחין ששכחת להפעיל את clearInterval.

challenge icon

אתגר

קל
  • remind <n> מדפיסה 3, 2, 1, ואז את הטקסט של הפתק n, שורה אחת בכל 200 ms, והתוכנית מסתיימת.
  • מספר שגוי מחזיר תשובה כמו done: No note <word> וקוד יציאה 1.

הריצו node notes.js remind 1, ואז node notes.js remind 9.

נסו בעצמכם

// כלי ההערות שלך מתחיל כאן.
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);
}

כל השיעורים ביחידה יסודות Node.js