JS/JS 공부

[JS] setTimeout 정해진 시간후 함수 실행

congs 2023. 4. 21. 09:52

setTimeout ( callback function , duration );

: duration 시간 후에 callback function 실행

  • setTimeout을 할당한 객체를 clearTimeout(할당한 객체)로 취소가 가능

 

사용

- 버튼을 누리면 3초 후에 나타나는 setTimeout 설정

 
 
<body>

    1초 = 1000 millisecond  /
    3초 = 3000

    <button type="button" id="start">시작</button>
    <button type="button" id="end"></button>
    <h1 id="result">3초후 글자 등장</h1>

    <script>
       
        let timeObj; //timeout을 설정할 객체

        //글자를 변경하는 함수
        function myFun(){
            document.getElementById('result').innerText = "등장했다. 3초뒤. 글자";
        }

        //시작 (setTimeout)
        document.getElementById('start').addEventListener('click',()=>{
            timeObj = setTimeout(myFun, 3000); //3초 = 3000

        })

        //끝(종료하기 clearTimeout)
        document.getElementById('end').onclick= () =>{
            clearTimeout(timeObj);
        }


    </script>