Coding 수업정리/드림코딩

[JS로 게임 만들기]카운트다운 타이머 만들기(참고자료)

kthdev 2023. 5. 29. 22:10

으아.... 

간단한 자바스크립트 게임 만들기 프로젝트를 시작했는데

게임은 커녕 카운트다운 타이머 만드는것 조차 이렇게 어렵다니

겨우 찾은 카운트다운 타이머 만들기 예제

https://www.youtube.com/watch?v=PIiMSMz7KzM 

https://codepen.io/dcode-software/pen/XWgyOpg

 

Easy Countdown Timer with JavaScript

Taken from my YouTube video: https://youtu.be/PIiMSMz7KzM In today's video we'll be building a simple countdown timer using HTML, CSS and JavaScript. ...

codepen.io

class Timer {
  constructor(root) {
    root.innerHTML = Timer.getHTML();

    this.el = {
      minutes: root.querySelector(".timer__part--minutes"),
      seconds: root.querySelector(".timer__part--seconds"),
      control: root.querySelector(".timer__btn--control"),
      reset: root.querySelector(".timer__btn--reset")
    };

    this.interval = null;
    this.remainingSeconds = 0;

    this.el.control.addEventListener("click", () => {
      if (this.interval === null) {
        this.start();
      } else {
        this.stop();
      }
    });

    this.el.reset.addEventListener("click", () => {
      const inputMinutes = prompt("Enter number of minutes:");

      if (inputMinutes < 60) {
        this.stop();
        this.remainingSeconds = inputMinutes * 60;
        this.updateInterfaceTime();
      }
    });
  }

  updateInterfaceTime() {
    const minutes = Math.floor(this.remainingSeconds / 60);
    const seconds = this.remainingSeconds % 60;

    this.el.minutes.textContent = minutes.toString().padStart(2, "0");
    this.el.seconds.textContent = seconds.toString().padStart(2, "0");
  }

  updateInterfaceControls() {
    if (this.interval === null) {
      this.el.control.innerHTML = `<span class="material-icons">play_arrow</span>`;
      this.el.control.classList.add("timer__btn--start");
      this.el.control.classList.remove("timer__btn--stop");
    } else {
      this.el.control.innerHTML = `<span class="material-icons">pause</span>`;
      this.el.control.classList.add("timer__btn--stop");
      this.el.control.classList.remove("timer__btn--start");
    }
  }

  start() {
    if (this.remainingSeconds === 0) return;

    this.interval = setInterval(() => {
      this.remainingSeconds--;
      this.updateInterfaceTime();

      if (this.remainingSeconds === 0) {
        this.stop();
      }
    }, 1000);

    this.updateInterfaceControls();
  }

  stop() {
    clearInterval(this.interval);

    this.interval = null;

    this.updateInterfaceControls();
  }

  static getHTML() {
    return `
			<span class="timer__part timer__part--minutes">00</span>
			<span class="timer__part">:</span>
			<span class="timer__part timer__part--seconds">00</span>
			<button type="button" class="timer__btn timer__btn--control timer__btn--start">
				<span class="material-icons">play_arrow</span>
			</button>
			<button type="button" class="timer__btn timer__btn--reset">
				<span class="material-icons">timer</span>
			</button>
		`;
  }
}

new Timer(
	document.querySelector(".timer")
);

 

 

간단한거에 class개념이 왜 들어갔는지 이해가 잘 안가서(아직 class개념이 부족한듯 하다 공부 필요.)..

더 간단한 아래 자료를 참고해서 만들었다.

 

 

https://codepen.io/Xand0r/pen/AMwpPr

 

Simple Countdown Timer Testing

Simple countdown timer using javascript. Testing for use in an HTML5 app....

codepen.io

var COUNT_START = 10*20; // tenths * seconds * hours
var count = COUNT_START;
var playing = false;

playpause = document.getElementById('playpause');
reset = document.getElementById('reset');

playpause.onclick = function() {
  if (playing) {
    playing = false; 
    console.log("Pause!");
    playpause.innerHTML = "▶";
  } else if (!playing) {
    playing = true; 
    console.log("Play!");
    playpause.innerHTML = "‖";
  }
  
}

reset.onclick = function() {
  if (playing) {
    playing = false; 
    playpause.innerHTML = "▶";
  }
  console.log("Reset Timer!");
  count = COUNT_START;
}

function countdown(){
    displayTime(); 
    if (count == 0) {
      playing = false;
    } else if (playing) {
      setTimeout(countdown, 100);
      count--;
    } else {
      setTimeout(countdown, 100); 
    }
}
countdown();

function displayTime() {
  
  var tenths = count;  
  var sec = Math.floor(tenths / 10);
  var hours = Math.floor(sec / 3600);
  sec -= hours * (3600);
  var mins = Math.floor(sec / 60);
  sec -= mins * (60);

  if (hours < 1) {
    document.getElementById('time_left').innerHTML = LeadingZero(mins)+':'+LeadingZero(sec);
  }
  else {
    document.getElementById('time_left').innerHTML = hours+':'+LeadingZero(mins)+':'+LeadingZero(sec);
  }
}

function LeadingZero(Time) {
  return (Time < 10) ? "0" + Time : + Time;
}