[Javascript] 시간 간격을 두고 함수 호출하기 (setTimeout / setInterval)
숫자맞추기 게임을 만들며 제한시간을 화면에 표시하고싶어 setInterval을 사용해보았다.
알아본 내용을 정리해보자.
setTimeout
사용법
지정한 시간만큼 기다렸다가 함수를 실행해야할 때 사용할 수 있다!
setTimeout(실행할 함수, 기다릴 시간);
setTimeout(() => {
console.log("1초 지남");
}, 1000);
setTimeout(foo, 3000);
function foo() {
console.log("3초 지남");
}
실행할 함수를 바로 작성해주거나 함수명을 적어주고, 기다릴 시간을 ms 단위로 작성해주면 된다. (1000ms == 1초)
clearTimeout
중간에 실행을 취소하고 싶은 경우 clearTimeout()을 사용하면 된다!
setTimeout을 실행할 때 ID가 반환되므로, 그 값을 저장해뒀다가 clearTimeout의 매개변수로 넘겨주면 된다.
let timeoutID = setTimeout(foo, 10000);
.
.
.
clearTimeout(timeoutID);
10초 후에 foo를 호출하기위해 시간을 재고있었지만, 그 전에 clearTimeout이 호출되면 시간 확인을 중단하고 foo는 호출되지 않는다.
setInterval
사용법
시간 간격을 두고 특정 함수를 주기적으로 호출하고싶을 때 사용한다.
setInterval(foo, 1000);
사용법은 setTimeout과 거의 비슷하다!
주기적으로 호출하고 싶은 함수와 그 주기를 ms 단위로 적어준다.
clearInterval
let intervalID = setInterval(foo, 1000);
.
.
.
clearInterval(intervalID);
일정 주기로 호출하는 것을 멈추기 위해서는 setInterval 호출시 반환된 ID를 clearInterval에 매개변수로 넘겨준다!
참고자료
MDN, setTimeout() global function
setTimeout() global function - Web APIs | MDN
The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
developer.mozilla.org
MDN, setInterval() global function
setInterval() global function - Web APIs | MDN
The setInterval() method, offered on the Window and WorkerGlobalScope interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
developer.mozilla.org