clearTimeout() 메서드는 이전에 setTimeout() 함수로 설정한 시간 초과를 지웁니다. clearInterval() 메서드는 setInterval() 함수로 이전에 설정한 간격을 지웁니다.
다음은 clearTimeout() 및 clearInterval() 메서드에 대한 코드입니다. -
예시
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.timeout {
margin-right: 170px;
display: inline-block;
width: 200px;
height: 200px;
}
.interval {
display: inline-block;
width: 200px;
height: 200px;
}
.stopTimeout {
margin-right: 100px;
}
</style>
</head>
<body>
<h1>clearTimeout() & clearInterval() Method</h1>
<div class="timeout" style="background-color: blue;"></div>
<div class="interval" style="background-color: blue;"></div>
<br />
<button class="startTimeout" onclick="startTimeout()">START TIMEOUT</button>
<button class="stopTimeout" onclick="stopTimeout()">STOP TIMEOUT</button>
<button class="startInterval" onclick="startInterval()">
START INTERVAL
</button>
<button class="stopInterval" onclick="stopInterval()">STOP INTERVAL</button>
<div class="resultInterval"></div>
<div class="resultTimeout"></div>
<script>
let resInterval = document.querySelector(".resultInterval");
let resTimeout = document.querySelector(".resultTimeout");
function changeColor(ele) {
if (ele.style.backgroundColor == "blue") {
ele.style.backgroundColor = "red";
} else {
ele.style.backgroundColor = "blue";
}
}
let timeout;
function startTimeout() {
timeout = setTimeout(
changeColor.bind(this, document.querySelector(".timeout")),
1500
);
resTimeout.innerHTML = "Timeout has been started";
}
function stopTimeout() {
clearTimeout(timeout);
resTimeout.innerHTML = "Timeout has been cleared";
}
let interval;
function startInterval() {
interval = setInterval(
changeColor.bind(this, document.querySelector(".interval")),
1500
);
resInterval.innerHTML = "Interval has been started";
}
function stopInterval() {
clearInterval(interval);
resInterval.innerHTML = "Interval has been cleared";
}
</script>
</body>
</html> 출력

"START TIMEOUT" 및 "START INTERVAL" 버튼을 클릭하고 몇 초를 기다리면 -

"STOP TIMEOUT" 및 "STOP INTERVAL" 버튼을 클릭하면 -
