setInterval ( callback function, interval duration )
: duration(mullisecond)를 주기로 지속적으로 callback function 호출
- clearInterval(할당받은 객체)로 중지
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setInterval method</title>
<style>
h1{
background-color: brown;
color: white;
}
</style>
</head>
<body>
<button type="button" id="start">시작</button>
<button type="button" id="end">끝</button>
<h1 id="h1">
냠냠
</h1>
<script>
let intervalObj;
//함수반복 실행 setInterval
function flashColor(){
intervalObj = setInterval(changeColor, 1000);
}
//함수 반복 해제 clearInterval
function stopColor(){
clearInterval(intervalObj);
}
//색상변경 함수
function changeColor(){
let h1 = document.getElementById('h1');
h1.style.color = (h1.style.color == 'white'? 'black' : 'white'); //색을 검정-하양 반복
h1.style.backgroundColor = (h1.style.backgroundColor == 'brown'? 'yellow' : 'brown');
}
//실행
document.getElementById('start').addEventListener('click',flashColor);
document.getElementById('end').addEventListener('click',stopColor);
</script>
</body>
</html>
'HTML.CSS.JS > JS' 카테고리의 다른 글
[JS] DOM ( Document Object Model ) : 문서(html) 객체 모델 (0) | 2023.04.21 |
---|---|
[JS] location 객체 사용 (url로 이동, 페이지 새로고침) (0) | 2023.04.21 |
[JS] setTimeout 정해진 시간후 함수 실행 (0) | 2023.04.21 |
[JS] day13_구구단 게임 (0) | 2023.04.20 |
[JS] day13_window_popup 팝업창 (0) | 2023.04.20 |