JS/JS 공부

[JS] setInterval 정해진 시간주기로 지속적 함수 호출

congs 2023. 4. 21. 10:26

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>