search

Home  >  Q&A  >  body text

javascript - JS countdown overlay problem

The following code is a simple timer. However, clicking the timing button more than two times in a row will cause the timing to accelerate and cannot be paused (cannot be stopped~~). What is the bug hidden in it? Need a solution?

<!DOCTYPE html>
<html>
<head>

<title>
    计时器
</title>
<style type="text/css">
    
    p {
        width: 400px;text-align:center;height: 500px;font-weight: 700;background-color: #ccc;font-size: 400px;margin: 0 auto;
    }
</style>

</head>
<body>

<p><font color="red" size="28"></font></p>

<input type="button" value="计时开始⌚️">
<input type="button" value="计时暂停⏸️">

<script type="text/javascript">
        //计时开始方法
        var i = 0;
        var times;
        var prebtn = document.getElementsByTagName("input")[0].onclick=function()
        {
                times = window.setInterval(function(){
            
                i++
                document.getElementsByTagName("p")[0].innerHTML=i;
            },1000);
        }
        //计时结束方法
        var nextbtn = document.getElementsByTagName("input")[1].onclick=function()
        {
            var cleartimes = window.clearInterval(times);
        }

</script>

</body>
</html>

天蓬老师天蓬老师2770 days ago599

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-05-18 10:48:32

    var prebtn = document.getElementsByTagName("input")[0].onclick=function()
            {
                    clearInterval(times);
                    times = window.setInterval(function(){
                
                    i++
                    document.getElementsByTagName("p")[0].innerHTML=i;
                },1000);
            }

    reply
    0
  • 阿神

    阿神2017-05-18 10:48:32

    Judge in the timing functiontimes 如果有值,直接返回;
    或者有值的情况下先clearInterval然后再重新setInterval

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-18 10:48:32

    Clicking 2 times is equivalent to setting 2 timers, so it will be a trap.

    reply
    0
  • Cancelreply