공부 정리/jsChallenge

js challenge day 29

경적필패. 2023. 3. 6. 14:42
반응형

Timer

Code

let countdown;
const timerDisplay = document.querySelector(".display__time-left");
const endTime = document.querySelector(".display__end-time");
const buttons = document.querySelectorAll("[data-time]");

const timer = (seconds) => {
  clearInterval(countdown);

  const now = Date.now();
  const then = now + seconds * 1000;
  displayTimeLeft(seconds);
  displayEndTime(then);

  countdown = setInterval(() => {
    {
      const secondLeft = Math.round((then - Date.now()) / 1000);
      if (secondLeft < 0) {
        clearInterval(countdown);
        return;
      }

      displayTimeLeft(secondLeft);
    }
  }, 1000);
};
const displayTimeLeft = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const remainderSeconds = seconds % 60;
  const display = `${minutes}:${remainderSeconds < 10 ? "0" : ""}${remainderSeconds}`;
  document.title = display;
  timerDisplay.textContent = display;
};

const displayEndTime = (timestamp) => {
  const end = new Date(timestamp);
  const hour = end.getHours();
  const adjustedHour = hour > 12 ? hour - 12 : hour;
  const minutes = end.getMinutes();
  endTime.textContent = `Be Back At ${adjustedHour}:${minutes < 10 ? "0" : ""}${minutes}`;
};

const startTimer = (e) => {
  const seconds = parseInt(e.target.dataset.time);
  timer(seconds);
};
buttons.forEach((button) => button.addEventListener("click", startTimer));
document.customForm.addEventListener("submit", (e) => {
  e.preventDefault();
  const mins = e.target.minutes.value;
  timer(mins * 60);
  e.target.reset();
});

배운 점 & 느낀 점

js를 이용해 타이머를 만드는 과제였습니다.

언젠가 이런 간단한 예제를 순수 js로 만들어보고 싶다는 생각이 있었기 때문에 재밌게 진행할 수 있었습니다.

원리는 간단한데, setInerval을 이용하여 1초마다 텍스트를 변경해 주는 것이었습니다.

반응형