freezner

[JS] setInterval을 적용하는 함수에 인자 추가하는 방법

주기적으로 함수를 실행시키기 위해 사용하는 setInterval 함수가 있습니다.

잘 아시겠지만 보통 이렇게 사용합니다.

<script type="text/javascript">
// test 함수를 5초마다 실행
setInterval(test, 5000);

function test() {
   console.log("hello!!");
}
</script>

 

여기서 test 함수에 인자가 포함되어있다면 어떻게 호출해야할까요? 방법은 아래와 같습니다.

<script type="text/javascript">
// test 함수를 5초마다 실행
setInterval(function(){
   test("hello");
}), 5000);

function test(string) {
   console.log(string);
}
</script>

 

이 방법을 통해 인자를 포함시켜 setInterval 을 실행시킬 수 있으며 여러 개의 함수를 함께 실행 시킬 수도 있습니다.

<script type="text/javascript">
// test 함수와 test2 함수를 5초마다 실행
setInterval(function(){
   test("hello");
   test2("hello2");
}), 5000);

function test(string) {
   console.log(string);
}

function test2(string) {
   console.log("test2 : " + string);
}
</script>

 

 

Exit mobile version