JavaScript에서 함수 실행을 중지하려면 clearTimeout() 메서드를 사용합니다. 이 함수 호출은 setTimeout() 함수에 의해 설정된 모든 타이머를 지웁니다.
예시
다음 코드를 실행하여 JavaScript에서 clearTimeout() 메서드를 사용하는 방법을 배울 수 있습니다.
<html>
<head>
<title>JavaScript clearTimeout() method</title>
<script>
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload = init;
//-->
</script>
</head>
<body>
<form>
<img id = "myImage" src = "/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type = "button" value = "Start" onclick = "moveRight();" />
<input type = "button" value = "Stop" onclick = "stop();" />
</form>
</body>
</html>