要在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>
登錄后復制
以上就是如何使用JavaScript停止函數的執行?的詳細內容,更多請關注www.92cms.cn其它相關文章!






