タイマー
CoddyのNode.jsジャーニー「Node.jsの基礎」セクションの一部。レッスン 27/33。
リマインダーは画面上で一段階ずつカウントダウンし、その後停止する必要があります。
setInterval(fn, ms)はclearInterval(id)で停止されるまで、fnをmsミリ秒ごとに実行します。setTimeoutは一度だけ実行します。タイマーが残っていないときにのみプログラムは終了するため、解除し忘れたインターバルはプログラムを実行し続けます。
let lap = 1;
const id = setInterval(() => {
console.log(`Lap ${lap}`);
lap += 1;
if (lap > 3) {
clearInterval(id);
}
}, 500);ターミナルは5秒後にプログラムを停止します。そのため、clearIntervalの解除し忘れに気づくことができます。
チャレンジ
簡単メモを表示する前に、画面上でカウントダウンします。タイマーを使ってこれを行う remind コマンドを追加しましょう。
notes.jsにremindコマンドを追加します。その後の単語はメモ番号です。doneと同じ方法で確認するので、noteNumberを再利用できます。- 遅延を200ミリ秒にして、
setIntervalを1つ開始します。呼び出されるたびに1行ずつ出力します。最初に3、次に2、その次に1、最後にメモのテキストを出力します。 - メモを出力した後、
clearIntervalでインターバルを停止し、プログラムを終了させます。
Buy milk と Call Ada というメモがある場合、node notes.js remind 2 を実行すると、200ミリ秒ごとに次の行が出力されます。
3
2
1
Call Ada- メモ番号ではない数値を指定すると、
doneの場合と同じようにエラーになります。メモが2つあるとき、node notes.js remind 9は標準エラー出力にNo note 9と出力して、カウントダウンせずに終了コード1で終了します。
試してみましょう: $ node notes.js の後にある入力欄に remind 1 と入力し、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プレイグラウンド