Menu
CoddyTech

Zamanlayıcılar

Coddy'nin Node.js Journey'sinin Node.js Temelleri bölümünün bir parçası. Ders 27 / 33.

Bir hatırlatıcı ekranda her seferinde bir adım geri saymalı ve sonra durmalıdır.

setInterval(fn, ms), clearInterval(id) onu durdurana kadar her ms milisaniyede bir fn işlevini çalıştırır; setTimeout ise bir kez çalışır. Bir program ancak geriye hiç zamanlayıcı kalmadığında sona erer; bu yüzden hiç temizlemediğiniz bir aralık, programın çalışmaya devam etmesine neden olur.

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

Terminal, bir programı 5 saniye sonra durdurur; unutulmuş bir clearInterval olduğunu bu şekilde fark edersiniz.

challenge icon

Görev

Kolay

Ekranda notu göstermeden önce bir hatırlatıcı geri sayım yapar. Bunu bir zamanlayıcıyla yapan bir remind komutu ekle.

  1. notes.js dosyasına bir remind komutu ekle. Komuttan sonraki sözcük bir not numarasıdır ve done komutundakiyle aynı şekilde denetlenir; bu nedenle noteNumber işlevini yeniden kullanabilirsin.
  2. 200 milisaniye gecikmeyle bir setInterval başlat. Her tikte bir satır yazdır: önce 3, sonra 2, ardından 1 ve son olarak notun metni.
  3. Notu yazdırdıktan sonra aralığı clearInterval ile durdur; böylece program sona erer.

Buy milk ve Call Ada notları varken, node notes.js remind 2 bu satırları her 200 milisaniyede bir yazdırır:

3
2
1
Call Ada
  1. Not numarası olmayan bir sayı, done komutunda olduğu gibi başarısız olur. İki not varken node notes.js remind 9, No note 9 ifadesini stderr'e yazdırır ve geri sayım yapmadan 1 çıkış koduyla çıkar.

Deneyin: $ node notes.js ifadesinden sonra kutuya remind 1 yazıp Enter'a basın. Geri sayımı, ardından ilk notunuzu görürsünüz. Sonra remind 9 yazın: kırmızı renkte No note 9 ifadesini ve 1 çıkış kodunu görürsünüz. clearInterval komutunu unutursanız program kendi kendine hiç sona ermez ve terminal 5 saniye sonra programı durdurur.

Kendin dene

// Not aracınız burada başlıyor.
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 Temelleri bölümündeki tüm dersler

Kendi başına pratik yap: Express playground