首頁  >  文章  >  web前端  >  如何使用JavaScript停止函數的執行?

如何使用JavaScript停止函數的執行?

王林
王林轉載
2023-09-15 12:37:021219瀏覽

如何使用JavaScript停止函數的執行?

要停止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停止函數的執行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除