development/html javascript CSS
[JavaScript] setTimeout() 시간 지연시켜 작업 수행 method
Happyoon ~
2021. 10. 15. 00:40
728x90
반응형
setTimeout은 일정 시간을 지연시켜 어떤 작업을 수행하기 위한 메서드이다.
사용법은 다음과 같다.
setTimeout(function(){}, delay) //(호출할 함수, 지연시간)
지연시간 단위는 1/1000초이다.
다음 예제는 setTimeout을 활용하여 5초 이후에 알림창을 띄우는 예제이다.
<!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>Step08_etc4.html</title>
</head>
<body>
<h1>일정시간 지연 시켜서 어떤 작업 수행하기</h1>
<button id = "alertBtn">5초 이후에 알림띄우기</button>
<script>
document.querySelector("#alertBtn").addEventListener("click",function(){
//setTimeout(호출될 함수, 지연시간)
setTimeout(function(){
alert("알림!");
},5000);
});
</script>
</body>
</html>
반응형