카테고리 없음
[JavaScript] setTimeout & setInterval
코드베어
2022. 1. 23. 20:06
일정 시간이 지난 뒤 함수를 실행 시키고 싶을 때, 혹은 일정시간마다 함수를 실행하고 싶을 때 setTimeout, setInterval 함수를 사용할 수 있다.
- setTimeout(func, milliseconds, arg1, arg2...) : milliseconds 후 func 함수를 실행. (arg1, arg2... 매개변수 전달)
- setInterval(func, milliseconds, arg1, arg2...) : milliseconds 마다 func 함수를 실행 (arg1, arg2... 매개변수 전달)
clearTimeout, clearInterval함수로 위에 등록된 함수 호출을 취소할 수 있다.
예시 )
// setTimeout
function OnTimeoutFunc(msg) {
console.log(`called ! : ${msg}`);
}
const id = setTimeout(OnTimeoutFunc, 3000, "after 3 seconds");
clearTimeout(id); // setTimeout 스케쥴링 취소 !
// setInterval
function OnIntervalFunc(msg) {
console.log(`called ! : ${msg}`);
}
const id2 = setInterval(OnIntervalFunc, 1000, "interval func called !");
clearInterval(id2); // setInterval 스케쥴링 취소 !