안녕하세요. 박기린 입니다.
이번에는 JS에서 타이머를 설정하는 방법에 대해 알아보겠습니다.
setTimeout()
const ingredients = ['olives', 'spinach'];
const pizzaTimer = setTimeout(
(ing1, ing2) => console.log(`Here is your pizza with ${ing1} and ${ing2} 🍕`),
3000,
...ingredients
);
setTimeout( 콜백함수, 밀리초, 콜백함수에 들어올 인수들 )
setTimeout()은 특정 시간이 지나면 콜백함수를 불러오는 JS 내장함수 입니다.
이때, 단 한 번만 콜백함수를 불러옵니다.
실행한 후 3초를 기다리면 함수가 실행됨을 확인할 수 있습니다.
clearTimeout()
const ingredients = ['olives', 'spinach'];
const pizzaTimer = setTimeout(
(ing1, ing2) => console.log(`Here is your pizza with ${ing1} and ${ing2} 🍕`),
3000,
...ingredients
);
console.log('Waiting...');
if (ingredients.includes('spinach')) clearTimeout(pizzaTimer);
clearTimeout( 실행을 취소할 setTimeout이 담긴 변수 or 상수 )
clearTimeout()은 setTimeout()의 두 번째 인수(밀리초)가 정한 시간이 지나가기 전에 취소해버리는 함수이다.
ingredients Array에 spinach가 있으면 clearTimeout()이 실행되도록 해놨습니다.
실제로 ingredients Array에 spinach가 있으니 pizzaTimer가 실행되지 않는 모습입니다.
setInterval()
setInterval(function () {
const now = new Date();
console.log(now);
}, 1000);
setInterval( 콜백함수, 밀리초 )
setInterval()은 두 번째 인수로 받은 n초마다 반복해서 콜백함수를 불러옵니다.
반응형
'JS > JavaScript 강의' 카테고리의 다른 글
[JS] 62. ES6 Class (0) | 2023.01.13 |
---|---|
[JS] 61. 생성자 함수와 new 연산자/프로토타입 상속과 체인 (0) | 2023.01.11 |
[JS] 59. Date 객체를 이용해서 날짜 계산하기 (0) | 2023.01.04 |
[JS] 58. 날짜 만들기 - Date (0) | 2023.01.03 |
[JS] 57. Bigint 타입 (0) | 2023.01.02 |