如何使用 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.