如何使用 JavaScript 停止函式執行?


若要停止 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>

更新於: 21-5-2020

9K+ 瀏覽

開啟你的 職業生涯

透過完成該課程獲得證書

開始學習
廣告
© . All rights reserved.