首页  >  文章  >  web前端  >  如何使用JavaScript停止函数的执行?

如何使用JavaScript停止函数的执行?

王林
王林转载
2023-09-15 12:37:021220浏览

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