[JavaScript] 스탑워치를 만들면서

김서진·2024년 2월 21일
post-thumbnail

스탑워치를 만들면서 실수한 부분이나 알게된 메소드 정리


html 코드

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>StopWatch</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div class="time-display">00 : 00 : 00</div>
      <div class="buttons">
        <button id="start">Start</button>
        <button id="stop">stop</button>
        <button id="reset">reset</button>
      </div>
    </div>

    <script src="script.js"></script>
  </body>
</html>

css 코드

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: Arial, sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.container {
  text-align: center;
}

.time-display {
  font-size: 2em;
  margin-bottom: 20px;
  color: red;
}

.buttons {
  display: flex;
  gap: 10px;
}

button {
  font-size: 1rem;
  padding: 10px 20px;
  cursor: pointer;
}

js 코드

let stopwatch;
let isRunning = false;
let elapsedTime = 0;

// 시간 표시하는 화면 업데이트
function updateDisplay() {
  const display = document.querySelector(".time-display");
  const seconds = Math.floor(elapsedTime / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);

  // 시, 분, 초를 두 자리수로 표시하여 문자열을 만든다.
  const formattedTime = `${String(hours).padStart(2, "0")} : ${String(
    minutes % 60
  ).padStart(2, "0")} : ${String(seconds % 60).padStart(2, "0")}`;
  display.textContent = formattedTime;
}

// 스탑워치 시작
function startStopwatch() {
  if (!isRunning) {
    isRunning = true;
    stopwatch = setInterval(() => {
      elapsedTime += 1000;
      updateDisplay();
    }, 1000);
  }
}

// 스탑워치 정지
function stopStopwatch() {
  if (isRunning) {
    isRunning = false;
    clearInterval(stopwatch);
  }
}

// 스탑워치 초기화
function resetStopwatch() {
  stopStopwatch();
  elapsedTime = 0;
  updateDisplay();
}

// 버튼에 이벤트 리스너 등록
document.getElementById("start").addEventListener("click", startStopwatch);
document.getElementById("stop").addEventListener("click", stopStopwatch);
document.getElementById("reset").addEventListener("click", resetStopwatch);

실수한점

document.getElementById("start").addEventListener("click", startStopwatch());

버튼에 이벤트 리스너 등록을 할때 startStopwatch()라고 넘겨줘서 페이지가 로드되자마자 함수가 실행되어버리는 문제가 발생했었다.

내가 원하는 이벤트가 발생할 때만 함수가 실행되게 하려면 startStopwatch()가 아닌 startStopwatch 형태로 넘겨주면 이벤트가 발생할 때만 함수가 실행된다.

함수 이름 뒤에 괄호를 붙이면 해당 함수를 즉시 호출하게 되므로, 이런 경우에는 함수 이름만 전달.


알게된 점

padStart메소드

현재 문자열의 시작을 다른 문자열로 채워서, 주어진 길이를 만족하는 새로운 문자열을 반환. 이때 채워넣기는 대상 문자열의 시작부터 적용.

// str.padStart(targetLength [, padString])
// targetLength-목표 문자열 길이, padString-현재 문자열에 채워넣을 다른 문자열

const str = '7';
console.log(str1.padStart(2, '0'));  // "07"

% 연산자

const seconds = 4

console.log(seconds % 60) // 4

왼쪽 피연산자가 오른쪽 피연산자보다 값이 작을때는 값이 그대로 나온다.

참고자료

0개의 댓글