JAVA SCRIPT
[Javascript] window 메소드 ( setTimeout, setInterval, clearInterval, clearTimeout )
혀누쓰0
2022. 6. 12. 11:37
https://hyunu0504.github.io/blog7/
https://hyunu0504.github.io/blog7/
hyunu0504.github.io
setTimeout, setInterval, clearTimeout, clearInterval를 이용한 버튼 만들기
HTML
<html>
<head>
<link rel="styleSheet" href="style.css" />
</head>
<body>
<div class="colors">5</div>
<button class="btn">5초 후부터 작동되는 버튼</button>
<div class="colors2"></div>
<button class="btn2">5초 후부터 작동안되는 버튼</button>
<script src="a.js"></script>
</body>
</html>
CSS
body {
background-color: #eee;
}
.colors {
background-color: grey;
height: 500px;
width: 500px;
}
.colors2 {
background-color: green;
height: 500px;
width: 500px;
}
.btn {
margin-right: 50px;
margin-bottom: 100px;
font-size: 32;
}
.btn2 {
font-size: 32;
}
.btn3 {
font-size: 32;
}
JAVASCRIPT( 5초후 부터 작동되는 버튼 )
//5초후 부터 작동되는 버튼
const btn = document.querySelector(".btn");
const colors = document.querySelector(".colors");
let count = 0;
const counter = setInterval(changeNum, 1000);
function changeColor() {
if (count == 1) {
colors.style.backgroundColor = "black";
}
}
btn.addEventListener("click", changeColor);
setTimeout(timer, 5000);
function timer() {
count++;
}
JAVASCRIPT( 몇초 남았는지 알림 )
let i = 5;
function changeNum() {
i--;
console.log(i);
btn.innerHTML = `${i}초 후부터 작동되는 버튼`;
btn2.innerHTML = `${i}초 후부터 작동안되는 버튼`;
if (i == 0) {
clearInterval(counter);
btn.innerHTML = "작동 o";
btn2.innerHTML = "작동 x";
}
}
JAVASCRIPT( 5초후 부터 작동안되는 버튼 )
const btn2 = document.querySelector(".btn2");
const colors2 = document.querySelector(".colors2");
let count2 = 0;
btn2.addEventListener("click", changeColor2);
function changeColor2() {
if (count2 != 1) {
colors2.style.backgroundColor = "powderblue";
}
}
function timer2() {
count2 = 1;
clearInterval(stop2);
}
const stop2 = setInterval(timer2, 5000);
setTimeout( 함수, ms )
setTimeout(timer, 5000);
function timer() {
count++;
}
timer라는 함수를 5초후에 실행시켜주는 코드
ms밀리초후에 함수를 한번 실행시켜주는 setTimeout( 함수, ms )
clearTimeout( setTimeout명 )
const stop = setTimeout(timer, 5000);
btn3.addEventListener("click", function () {
clearTimeout(stop);
});
stop이란 명을가진 setTimeout을 종료시켜주는 코드다
ms밀리초 후에 실행하는 setTimeout()을 종료시켜주는 clearTimeout( setTimeout명 )
setInterval( 함수, ms)
function timer2() {
count2 = 1;
}
const stop = setInterval(timer2, 5000);
timer2라는 함수를 5초마다 실행시켜주는 코드
ms밀리초마다 함수를 실행시켜주는 setInterval( 함수, ms )
clearInterval( setInterval명 )
function timer2() {
count2 = 1;
clearInterval(stop);
}
const stop = setInterval(timer2, 5000);