Menu
CoddyTech

타이머

Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 24개 중 19번째.

알림은 화면에서 한 번에 한 단계씩 카운트다운한 다음 멈춰야 합니다.

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을 빠뜨렸다는 것을 알 수 있습니다.

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 기초의 모든 레슨