使用 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>

更新於:2020 年 5 月 21 日

9K+ 瀏覽次數

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.