要停止在JavaScript中执行功能,请使用clearTimeout()
方法。该函数调用清除功能设置的任何计时器setTimeout()
。
您可以尝试运行以下代码,以了解如何使用clearTimeout()
JavaScript中的方法。
<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>