coding/web

javascript Timer 타이머 SetTimeout(), clearTimeout()

100a 2021. 6. 24. 21:39

 

javascript로 짠 간단한 타이머 프로그램입니다.

타이머 gif

<h1>Timer</h1>
<h2>Timer</h2>
<br />
<a href="#" class="startbtn">시작</a>
<a href="#" class="stopbtn">일시정지</a>
let txtArea = document.querySelector('h2');
let startEl = document.querySelector('.startbtn');
let stopEl = document.querySelector('.stopbtn');
let state = false;
let timer;

let count=0;
let timerId;
timer = {
  run: function (){
    clearTimeout(timerId);
    txtArea.textContent = count++;
    timerId = setTimeout(timer.run,  1000);
  },
  stop: function(){
    clearTimeout(timerId);
  }
}


timerId = setTimeout(timer.run,  1000);

startEl.addEventListener('click',function(event){
  timer.stop();
  setTimeout(timer.run,  1000);
});

stopEl.addEventListener('click',function(event){
  timer.stop();
});