Menu
CoddyTech

타이머

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

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

setInterval(fn, ms)는 clearInterval(id)이 중지할 때까지 ms밀리초마다 fn을 실행하고, 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. 지연 시간이 200밀리초인 setInterval 하나를 시작하세요. 매 틱마다 한 줄씩 출력합니다. 먼저 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는 stderr에 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 플레이그라운드