带有启动&的javascript倒数计时器停止按钮 [英] javascript countdown timer with start & stop buttons

查看:99
本文介绍了带有启动&的javascript倒数计时器停止按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用从5到0的简单倒数计时器,并使用按钮开始和停止计数器。我唯一不知道的是为什么我的计数器不会停止。

I need to make a simple countdown timer from 5 to zero, with the buttons to START and STOP the counter. The only thing that I don't know is that why won't my counter stop.

代码如下:

   function clock() {
     var myTimer = setInterval(myClock, 1000);
     var c = 5;

     function myClock() {
       document.getElementById("demo").innerHTML = --c;
       if (c == 0) {
         clearInterval(myTimer);
         alert("Reached zero");
       }
     }
   }

<p id="demo">5</p>
<button onclick="clock()">Start counter</button>
<button onclick="clearInterval(myTimer)">Stop counter</button>

推荐答案

在这里,您只需要使 myTimer 全局。我还修复了重置计时器后不会显示5的故障。

Here you go, you just needed to make myTimer global. I also fixed a glitch where after resetting the timer, it won't show 5.

var myTimer;
   function clock() {
     myTimer = setInterval(myClock, 1000);
     var c = 5;

     function myClock() {
       document.getElementById("demo").innerHTML = --c;
       if (c == 0) {
         clearInterval(myTimer);
         alert("Reached zero");
       }
     }
   }

<p id="demo">5</p>
<button onclick="clock(); document.getElementById('demo').innerHTML='5';">Start counter</button>
<button onclick="clearInterval(myTimer);">Stop counter</button>

这篇关于带有启动&amp;的javascript倒数计时器停止按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆