Javascript

setInterval, clearInterval 함수 활용 예제(시간이 지나면 사라지는 박스)

breeghty 2023. 2. 20. 21:02

See the Pen setTimeout(), setInterval() by breeghty (@breeghty) on CodePen.

 

setInterval 함수 사용방법

setInterval(function(){}, ms)

setInterval(function(){
	console.log("hello world!");
    },1000)
//1초에 한번씩 콘솔창에 hello world가 출력된다.

 

setInterval 함수 중지 방법(clearInterval(변수))

//1. 변수를 할당한다.
let timerFunc = setInterval(function(){
  document.getElementById('numCount').innerHTML=count;
  count--;
  console.log(count);
  if(count == -1){
    document.querySelector('.alert').style.display = 'none';
// 2.종료하고 싶은 시점에 clearInterval(setInterval을 할당한 변수)를 호출한다.
    clearInterval(timerFunc);
  }
},1000);