有点Bug。。点了stop后停止,再点2次start后再点stop就停止不了了....

来源:8-4 取消计时器clearInterval()

流星雨_1

2015-09-26 23:24

<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>计时器</title>

<script type="text/javascript">

i=setInterval("clock()",1000);

   function clock(){

      var time=new Date();                

      document.getElementById("clock").value = time;

   }

     

function mystart(){

i=setInterval("clock()",1000);

}

    function myclear(){

        clearInterval(i);

    }

</script>

</head>

<body>

  <form>

    <input type="text" id="clock" size="50"  />

    <input type="button" value="Stop" onclick="myclear()" />

<input type="button" value="Start" onclick="mystart()" />


  </form>

</body>

</html>


写回答 关注

2回答

  • 流星雨_1
    2015-09-27 12:07:40

    是的,谢谢楼上的回答~^O^   给我了一个思路。你这个代码运行后如果先点一次start后还是停止不了...

    下边是在你基础上改进的:

    <!DOCTYPE HTML>

    <html>

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <title>计时器</title>

    <script type="text/javascript">

    var i=setInterval("clock()",1000);

    var count = 0;

       function clock(){

          var time=new Date();                

          document.getElementById("clock").value = time;

          console.log(time);

       }

       function mystart(){

        if(count > 0 ){

           i=setInterval("clock()",1000); 

      count--;

        }

    }

        function myclear(){

            clearInterval(i);

            count = 1;

        }

    </script>

    </head>

    <body>

      <form>

        <input type="text" id="clock" size="50"  />

        <input type="button" value="Stop" onclick="myclear()" />

    <input type="button" value="Start" onclick="mystart()" />

     

      </form>

    </body>

    </html>


  • Y_du
    2015-09-27 07:56:16

    这个问题是,你点击了多次开始。想到开启了多个定时器。而你在关的时候只关了一个。所以会导致关不了。

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>计时器</title>
    <script type="text/javascript">
    i=setInterval("clock()",1000);
       function clock(){
          var time=new Date();                
          document.getElementById("clock").value = time;
          console.log(time);
       }
         
         var count = 0;
    function mystart(){
        if(count == 0){
           i=setInterval("clock()",1000); 
        }
        count = 1;
    }
        function myclear(){
            clearInterval(i);
            count = 0;
        }
    </script>
    </head>
    <body>
      <form>
        <input type="text" id="clock" size="50"  />
        <input type="button" value="Stop" onclick="myclear()" />
    <input type="button" value="Start" onclick="mystart()" />
    
      </form>
    </body>
    </html>

    这样是一个不优雅的解决办法

JavaScript进阶篇

本课程从如何插入JS代码开始,带您进入网页动态交互世界

467385 学习 · 21877 问题

查看课程

相似问题