본문 바로가기
카테고리 없음

[JS /자바스크립트] setInterval⏱, clearInterval⏱ / 주기별로 실행하기

by 서상혁 2020. 1. 1.

setInterval() 이란?

일정한 간격으로 함수를 실행할 수 있게끔 해줍니다.

setInterval(handler, 시간)

시간은 1ms 단위이며, 1초마다 실행시키고싶으면 1000ms 를 쓰면 됩니다.

* handler 는 반복적으로 실행할 함수

 

clearInterval() 이란?

setInterval 로 주기적으로 실행했던 것을 멈추게 합니다.

clearInterval(setInterval로 생성된 함수)

 


 

이를 이용한 시간을 나타내주는 예시 코드입니다.

 

HTML 파트

  <body>
    <h1 id="title" class="btn"> Hello. Click here!</h1>
    <div class="js-clock">
        <h1 class="js-title">00:00</h1>
    </div>
    <button onclick="stopTime()">Stop Time</button>
    <script src="./clock.js"> </script>
  </body>

JS 파트

const clockContainer = document.querySelector(".js-clock");
    clockTitle = clockContainer.querySelector("h1");

function getTime(){
    const date = new Date();
    const minutes = date.getMinutes();
    const hours = date.getHours();
    const seconds = date.getSeconds();
    clockTitle.innerText =`${hours}:${minutes}:${seconds}`;
    console.log("getTime"); 
}

function stopTime(){
    if(clockID != null){
        clearInterval(clockID);
        console.log("stopTime");
    }
}

function init(){
    getTime();
    clockID = setInterval(getTime,1000);
}

init();

728x90

댓글