Menu
CoddyTech

טיימרים

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

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

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 שעושה זאת באמצעות טיימר.

  1. ב־notes.js, הוסיפו פקודת remind. המילה שאחריה היא מספר של הערה, שנבדק באותו אופן כמו ב־done, כך שאפשר להשתמש שוב ב־noteNumber.
  2. הפעילו setInterval אחד עם השהיה של 200 אלפיות השנייה. בכל פעימה הודפסה שורה אחת: תחילה 3, אחר כך 2, אחר כך 1, ואז הטקסט של ההערה.
  3. אחרי הדפסת ההערה, עצרו את המרווח באמצעות clearInterval, כדי שהתוכנית תסתיים.

עם ההערות Buy milk ו־Call Ada, הפקודה node notes.js remind 2 מדפיסה את השורות האלה, אחת בכל 200 אלפיות השנייה:

3
2
1
Call Ada
  1. מספר שאינו מספר של הערה גורם לכישלון באותו אופן כמו ב־done. כשיש שתי הערות, הפקודה node notes.js remind 9 מדפיסה את No note 9 אל stderr ומסתיימת עם קוד 1, בלי לספור לאחור.

נסו זאת: הקלידו remind 1 בתיבה שאחרי $ node notes.js והקישו Enter. תראו את הספירה לאחור ואז את ההערה הראשונה שלכם. לאחר מכן הקלידו remind 9: תראו את No note 9 באדום ואת קוד היציאה 1. אם תשכחו את clearInterval, התוכנית לא תסתיים מעצמה, והמסוף יעצור אותה אחרי 5 שניות.

נסו בעצמכם

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

תרגלו בעצמכם: Express אונליין