Handling time intervals in JavaScript - Lee-hyuna/33-js-concepts-kr GitHub Wiki

Handling time intervals in JavaScript

Electron app Formolectron์—์„œ ์ž‘์—…ํ•˜๋Š” ๋™์•ˆ ๋‚˜๋Š” ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ setInterval() ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ๋‹ค๋ฅธ ์‹œ๊ฐ„ ๊ฐ„๊ฒฉ์„ ๋‹ค๋ฃฐ ํ•„์š”๊ฐ€ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค.
๊ธฐ๋ณธ์ ์œผ๋กœ ๋‚ด ์•ฑ์— ์„ธ ๊ฐœ์˜ ํƒ€์ด๋จธ๋ฅผ ๊ตฌํ˜„ํ•ด์•ผ ํ–ˆ์Šต๋‹ˆ๋‹ค.

  • Pomodoro of 25 minutes
  • Short break of 5 minutes
  • Long break of 10 minutes

์„ธ ๊ฐ€์ง€ ๊ฒฝ์šฐ ๋ชจ๋‘ ์นด์šดํŠธ ๋‹ค์šด ํƒ€์ด๋จธ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์„ ์ƒ๊ฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
ํ•˜๋‚˜๋Š” ์„ธ ๊ฐ€์ง€ ๋‹ค๋ฅธ setInterval()์„ ์‚ฌ์šฉํ•˜์—ฌ ๋‹ค๋ฅธ ํƒ€์ด๋จธ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.
๋‘˜์งธ๋กœ๋Š” ์„ธ ํƒ€์ด๋จธ ๋ชจ๋‘ ๋™์ผํ•œ setInterval()์„ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์ฐพ๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฐฉ๋ฒ•์œผ๋กœ๋„ ์ข‹์Šต๋‹ˆ๋‹ค.
ServiceWorker๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ simple offline-capable Notepad app ๋งŒ๋“ค๊ธฐ

Solution(ํ•ด๊ฒฐ์ฑ…)

๊ทธ๋ž˜์„œ, ๋‚˜๋Š” ๋‘ ๋ฒˆ์งธ ์ ‘๊ทผ๋ฒ•์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.
์•„๋ž˜์™€ ๊ฐ™์€ ๋ณ€์ˆ˜์— ํ• ๋‹นํ•˜์—ฌ ์„ธ ๊ฐœ์˜ ํƒ€์ด๋จธ ๋ชจ๋‘์— ๋™์ผํ•œ setInterval()์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

var pomodoroIntervalId;

function startTimer(duration, display) {
  timer = duration;
  pomodoroIntervalId = setInterval(function(){
    if (--timer < 0) {
        timer = duration;
    }
    
    minutes = parseInt(timer/60, 10);
    seconds = parseInt(timer%60, 10);

    minutes = minutes < 10 ? '0'+minutes : minutes;
    seconds = seconds < 10 ? '0'+seconds : seconds;

    display.textContent = minutes+ ":" + seconds;

    if(minutes == 0 && seconds == 0){
      notifyUser();
    }
  }, 1000);
}

๋จผ์ € clearInterval()๋ฉ”์†Œ๋“œ๋กœ interval ID๋ฅผ ์ „๋‹ฌํ•˜์—ฌ ํ˜„์žฌ ์‹œ๊ฐ„ ๊ฐ„๊ฒฉ์„ ํด๋ฆฌ์–ดํ•จ์œผ๋กœ์จ ๋‹ค๋ฅธ ํƒ€์ด๋จธ ๊ฐ„์— ๋™์ผํ•œ startTimer()๋ฅผ ํ™œ์šฉํ•ฉ๋‹ˆ๋‹ค. ์šฐ๋ฆฌ์˜ ๊ฒฝ์šฐ์—๋Š” ์ „์—ญ๋ณ€์ˆ˜ pomodoroIntervalId์— ํ• ๋‹น ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด๊ฒƒ์€ ๊ธฐ๋ณธ์ ์œผ๋กœ ํ˜„์žฌ ์‹คํ–‰์ค‘์ธ interval์„ ์‚ญ์ œํ•˜์—ฌ ๋‹ค์Œ์— ๋‹ค๋ฅธ ํƒ€์ด๋จธ๊ฐ€ ์„ค์ •๋  ๋•Œ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ฉ๋‹ˆ๋‹ค. ์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

function resetTimer() {
  clearInterval(pomodoroIntervalId);
}

์ด๋ ‡๊ฒŒํ•˜๋ฉด ์ฝ”๋“œ๋ฅผ ๊นจ๋—ํ•˜๊ณ  ๋งค๋„๋Ÿฝ๊ฒŒ ๋งŒ๋“ค๋ฉฐ ๋™์ผํ•œ setInterval() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉ ํ•  ์ˆ˜์žˆ๋Š” ์ด์ ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ ์ •๋ง ํŽธ๋ฆฌํ•œ ๊ธฐ๋Šฅ์ด๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.