如何重置秒表多次停止观看时间?

时间:2014-02-10 04:58:06

标签: javascript timer

我试图通过使用锚标签来使用多个秒表计时器。我已成功完成但我无法添加功能,如果我点击第一个计时器,它将从零启动计时器,当我点击第二个,第一个计时器的值将为零,第二个计时器将从零开始计时器。我将在下面给出我的工作代码:

JS:

var digit=0;
    var hrs = 0;
    var min=0;
    var time;
    var timer_is_on=0;
    var id;

    function timer(id){
        //[Old] - this should be placed after you increment digit
        // document.getElementById("secs").innerHTML = digit
        //alert("I am testing value"+id);
        //[New]
        // get the numerical value for seconds,minutes,hours
        digit = parseInt(document.getElementById("secs"+id).innerHTML);
        min   = parseInt(document.getElementById("mins"+id).innerHTML);
        hrs   = parseInt(document.getElementById("hrs"+id).innerHTML);
        // increment;
        digit=digit+1;    


        if(digit>"59"){
            min = parseInt(min)+1;
            // why is this code here
            var count = min.toString().length;
            digit=0;
        }
        // [old] checking if second is greater than 59 and incrementing hours
        // if(digit>"59"){

        // [new] check if minute is greater than 59
        if(min > "59"){
            hrs=parseInt(hrs)+1;        
            digit=0;
            min=0; // minute should be reset as well
        }
         // set the values after all processing is done
        document.getElementById("secs"+id).innerHTML = format(digit);
        document.getElementById("mins"+id).innerHTML= format(min);
        document.getElementById("hrs"+id).innerHTML=format(hrs);
    }

        function activate(id){
        if(!timer_is_on){
            timer_is_on=1;
            // time = setTimeout("timer()",1000) will only call it once , use setInterval instead
            time=setInterval("timer("+id+")",1000);
        }
        else {
            timer_is_on=0;
            clearInterval(time); // clear the timer when the user presses the button again and reset timer_is_on
        }
        return id;
    }

    // left pad zero if it is less than 9
    function format(time){
        if(time > 9)
            return time;
        else return "0"+time;
    }

我使用的HTML代码是:

<a href="#" onclick="activate(1)">Click here to start the timer</a>
    <span id="hrs1" >00</span>:<span id="mins1" >00</span>:<span id="secs1">00</span></strong>
    <br/>
    <a href="#" onclick="activate(2)">Click here to start the timer</a>
    <span id="hrs2" >00</span>:<span id="mins2" >00</span>:<span id="secs2">00</span>

这是我工作的js小提琴演示:http://jsfiddle.net/EPtFW/1/

1 个答案:

答案 0 :(得分:0)

当您使用相同的方法activate()启动第二个计时器时,如果计时器已经运行,它将使第一个计时器为零。

解决方案是“你必须为多个计时器维护多个独特的计时器ID”

例如,假设你有T1和T2计时器来开始时间;

var timerMap={};
timerMap[createUniqueId for T1] = setInterval();
timerMap[createUniqueId for T2] = setInterval();

to clear timers
clearInterval(timerMap[createUniqueId for T1]);
clearInterval(timerMap[createUniqueId for T2]);

在你的情况下,你必须有createUniqueId,并且添加到timerMap应该在activate()方法中。他们将独立工作。