如何使用JavaScript停止函数的执行?

原创
ithorizon 7个月前 (10-19) 阅读数 33 #HTML

要在JavaScript中停止函数的执行,请使用clearTimeout()方法。此函数调用会清除由setTimeout()函数设置的任何定时器。

示例

您可以尝试运行以下代码,了解如何在JavaScript中使用clearTimeout()方法。

<html>
   <head>
      <title>JavaScript clearTimeout() method</title>
      <script>
         <!--
            var imgObj = null;
            var animate ;
           
            function init(){
               imgObj = document.getElementById(&#39;myImage&#39;);
               imgObj.style.position= &#39;relative&#39;;
               imgObj.style.left = &#39;0px&#39;;
            }
            function moveRight(){
               imgObj.style.left = parseInt(imgObj.style.left) + 10 + &#39;px&#39;;
               animate = setTimeout(moveRight,20);    // call moveRight in 20msec
            }
            function stop(){
               clearTimeout(animate);
               imgObj.style.left = &#39;0px&#39;;
            }
            window.onload = init;
         //-->
      </script>
   </head>
   <body>
      <form>
         <img  id = "myImage" src = "/images/html.gif" / alt="如何使用JavaScript停止函数的执行?" >
         <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停止函数的执行?的详细内容,更多请关注IT视界其它相关文章!



热门