setTimeout() 을 사용하여 시간을 설정한 경우 함수를 선택한 다음 JavaScript clearTimeout() 함수를 사용하여 지울 수 있습니다.
예시
다음 코드를 실행하여 JavaScript에서 clearTimeout() 함수를 구현하는 방법을 배울 수 있습니다. -
<html>
<head>
<title>JavaScript Animation</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>