setInterval() 사용법

setInterval() 함수는 어떤 코드를 일정한 시간 간격을 두고 반복해서 실행하고 싶을 때 사용합니다. 함수 API는 setTimeout() 함수와 대동소이한데요. 첫번째 인자로 실행할 코드를 담고 있는 함수를 받고, 두번째 인자로 반복 주기를 밀리초(ms) 단위로 받습니다.

 

ex)

setInterval() 함수를 사용하여 콘솔에 현재 시간을 2초마다 출력

setInterval(() => console.log(new Date()), 2000);

2초마다 현재 시각 출력

 

코드

html, javascript

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>타이머</title>

    <link rel="stylesheet" href="css/타이머.css" />
  </head>

  <body>
    <div id="container">
      <form>
        <label><input type="text" id="startMin" />분</label>
        <label><input type="text" id="startSec" />초</label>
        <button class="start-btn" onclick="startTimer()" type="button">
          START
        </button>
        <button class="reset-btn" onclick="resetTimer()" type="button">
          RESET
        </button>
      </form>

      <div id="display" class="remaining"></div>
      <div class="cnt_bar">
        <div class="cnt"></div>
      </div>
    </div>

    <script>
      // 자스는 데이터가 입력될때 형이 결정된다.
      let min = "";
      let sec = "";
      let timerId = "";
      let totalSec;
      let curTotalSec;
      document.querySelector(".cnt").style.width = "0%";

      function startTimer() {
        min = document.querySelector("#startMin").value;
        sec = document.querySelector("#startSec").value;
        // 분 초 입력 태그에 빈 값이면 0
        if (min == "") {
          min = 0;
        }
        if (sec == "") {
          sec = 0;
        }

        // 화면에 분 초 출력
        document.querySelector("#display").innerText = `${min} : ${sec}`;
        document.querySelector(".cnt").style.width = "100%";
        // 분,초 를 총 ?초로 변경 -> 타이머 바 생성 위함
        totalSec = Number(sec) + Number(min) * 60;

        // setInterval(실행할 코드, 반복주기)
        // --> countTime 메서드를 1초 주기마다 실행
        timerId = setInterval(countTime, 1000);
      }

      function countTime() {
        // 현재 초가 0초가 아니면
        if (sec != 0) {
          sec--;
          // 현재 분, 초 를 총 ?초로 변경 -> 타이머 바 줄어드는 것 출력
          curTotalSec = Number(sec) + Number(min) * 60;
          document.querySelector(".cnt").style.width = (curTotalSec / totalSec) * 100 + "%";
          document.querySelector("#display").innerText = `${min} : ${sec}`;
        } 
        // 현재 초가 0초이면
        else {
          // 현재 분이 0분이 아니면 
          if (min != 0) {
            sec = 59;
            min--;
          } 
          // 현재 분, 초가 다 0이면 타이머 종료
          else {
            terminateTimer(timerId);
          }
        }
      }

      // 타이머 초기화
      function terminateTimer(t) {
        clearInterval(t);
        document.querySelector("#startMin").value = "";
        document.querySelector("#startSec").value = "";
        document.querySelector("#display").innerText = "";
        document.querySelector(".cnt").style.width = "0%";
      }

      function resetTimer() {
        terminateTimer(timerId);
      }
    </script>
  </body>
</html>

 

css

@font-face {
  font-family: bm;
  src: url(../font/bamin/BMEuljiro10yearslater.ttf);
}

* {
  font-family: bm;
  font-size: 20px;
}

#container {
  width: 70%;
  margin: 0 auto;
  border: 3px dashed #aaa;
  text-align: center;
}
form {
  width: 100%;
  /* background-color: aliceblue; */
  padding: 10px;
}

form input {
  width: 100px;
  margin-left: 20px;
}

form button {
  margin-left: 20px;
}

form button:hover {
  background-color: black;
  color: white;
}

#display {
  border-top: 3px dashed #aaa;
  width: 100%;
  height: 200px;
  font-size: 25px;
  /* background-color: aqua; */
}

.cnt_bar {
  width: 70%;
  height: 40px;
  margin: 0 auto;
  margin-bottom: 40px;
  background-color: darkblue;
  border-radius: 5px;
}

.cnt {
  height: 40px;
  background-color: #f6f656;
  border-radius: 5px;
}

#display {
  padding-top: 70px;
  font-size: 40px;
  /* background-color: #aaa; */
  height: 100px;
}

img {
  width: 50px;
  height: 50px;
}

 

실행화면

타이머 실행화면

 

 

 

- Just Do It -

 

 

반응형
복사했습니다!