JavaScript 函式 clearTimeout() 的作用是什麼?


如果你已使用 setTimeout() 函式設定了時間,則你可以使用 JavaScript clearTimeout() 函式清除它。

示例

你可以嘗試執行以下程式碼以瞭解如何在 JavaScript 中實現 clearTimeout() 函式 −

<html>
   <head>
      <title>JavaScript Animation</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>

更新時間:23-6 月-2020

230 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.