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>
'HTML.CSS.JS > JS' 카테고리의 다른 글
[JS] location 객체 사용 (url로 이동, 페이지 새로고침) (0) | 2023.04.21 |
---|---|
[JS] setInterval 정해진 시간주기로 지속적 함수 호출 (0) | 2023.04.21 |
[JS] day13_구구단 게임 (0) | 2023.04.20 |
[JS] day13_window_popup 팝업창 (0) | 2023.04.20 |
[JS] day13_BOM (window.innerHeight/window.innerWidth) (0) | 2023.04.20 |