에르노트

[자바스크립트] 타이머 함수 사용하기 본문

Web/Javascript

[자바스크립트] 타이머 함수 사용하기

두콩 2020. 8. 15. 16:06

자바스크립트에서 일정 시간마다 특정한 동작을 수행하고 싶을 때는 자체적으로 제공되는(내장 함수) 타이머 함수를 사용할 수 있다.

 

- setInterval() 일정 시간마다 주기적으로 특정 구문을 실행하는 기능

- setTimeout() 일정 시간이 지난 후 특정 구문을 딱 한번 실행하는 기능

- clearInterval() 실행중인 타이머 함수를 멈추는 기능

 

setInterval()

 

WindowOrWorkerGlobalScope.setInterval()

The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

developer.mozilla.org

일정 시간마다 특정 구문을 실행할 수 있다. setInterval(function, time)의 형태로 사용한다. function에는 미리 정의해둔 함수 이름을 적어도 좋고 즉석에서 익명 함수를 만들어 넣을 수도 있다. 이때 time의 단위는 millisecond이므로 1초당 1000씩 넣는다고 생각하면 된다. 반환 값은 임의로 생성되는 id인데 이것을 clearInterval()의 인자로 넣으면 주기적인 동작을 멈출 수 있다.

 

setTimeout()

 

WindowOrWorkerGlobalScope.setTimeout()

The setTimeout() method of the WindowOrWorkerGlobalScope mixin (and successor to Window.setTimeout()) sets a timer which executes a function or specified piece of code once the timer expires.

developer.mozilla.org

위에서 살펴본 setInterval()이 특정 시간을 주기로 계속해서 동작을 반복시킨다면 setTimeout()은 특정 시간 후에 동작을 딱 한번만 발생시킨다. 역시 반환 값으로 임의의 id를 뱉어주고 후술할 clearInterval() 또는 clearTimeout()으로 취소할 수 있다.

 

clearInterval()

 

WindowOrWorkerGlobalScope.clearInterval()

The clearInterval() method of the WindowOrWorkerGlobalScope mixin cancels a timed, repeating action which was previously established by a call to setInterval().

developer.mozilla.org

타이머 함수에 부여되는 id를 통해서 그 동작을 멈춘다. clearTimeout()이라는 메서드가 따로 있기 때문에 원칙상 setInterval()에 대응하는 메서드이다. 하지만 setInterval()과 setTimeout()이 생성하는 id 값은 동질하기 때문에 그냥 함수를 멈추고자 할 때 언제든 사용할 수 있다.

 

 

예제

 

이를 응용해서 매우 간단한 예제를 작성해보았다. setInterval()과 clearInterval()을 이용하여 10초동안 count를 찍고, 미리 걸어둔 setTimeout()을 이용하여 11초 후에 "끝"이라는 문구를 출력한다.

var count = 0

var id = setInterval(function(){
  if(count < 10)
    console.log(++count);
  else
    clearInterval(id);
}, 1000);

setTimeout(()=>console.log("끝"), 11000);

예제 출력

 

Comments