使用我的javascript秒表无法获得暂停功能

时间:2013-09-15 18:34:37

标签: javascript

有人可以帮助我。我似乎无法让这个秒表暂停并显示暂停(停止)的时间,然后当我再次开始时重新激活。

我不知道如何阻止计时器计数。不确定最佳做法是结束计时器功能,为当前时间创建新函数,还是使用setInterval从中减去1?

<script type="text/javascript">
var digit=-1.0;
var min=0;
var time;


function timer(){
        digit++;       

        if(digit>59){
                min++;
                document.getElementById("mins").innerHTML=padTimer(min);
                digit=0;
        }
        document.getElementById("secs").innerHTML=padTimer(digit);  
}

function padTimer(x) {
        if (x<=9) { x = ("0"+x); }
        return x;
}  

function start(){
                time=setInterval(timer, 1000);
                timer();
}

function pause() {
}

function reset(){
            digit=-1.0;
            timerPay=0;              
}

</script>

<a href="#" onclick="start()">Click here to start the timer</a>
<a href="#" onclick="pause()">Click here to pause the timer</a>

<a href="#" onclick="reset()">Click here to reset the timer</a>

<div>
<span id="mins" >00</span>:<span id="secs">00</span><br>
</div>

4 个答案:

答案 0 :(得分:1)

function pause() { clearInterval(time); }

答案 1 :(得分:1)

使用clearInterval(time)删除间隔。

http://jsfiddle.net/tQE5p/

答案 2 :(得分:1)

因为时间变量发生了间隔,所以你应该在暂停函数中使用clearInterval(time)

答案 3 :(得分:1)

毫无疑问,clearInterval是您的答案,但您的代码中存在严重错误:如果用户多次点击开始按钮会发生什么情况(线索:注册了很多时间间隔)?< / p>

我为你写了一个更合理的constructor function。当用户点击start时,timerStarted会更改为true,反之亦然。 另外,由于它是constructor function,因此没有全局变量(Timer函数本身除外),您可以根据需要创建计时器。每个计时器应由new保留关键字创建。

function Timer (intervalSeconds) {
    this.__intervalSeconds = intervalSeconds;
    this.reset();
};

Timer.prototype.start = function () {
    if (!this.__timerStarted) {
        var self = this;

        this.__timerEventRegistered = setInterval(function() {
            self.timeElapsed += self.__intervalSeconds;
        }, this.__intervalSeconds);
    }
    this.timerStarted = true;
};

Timer.prototype.pause = function () {
    clearInterval(this.__timerEventRegistered);
    this._timerStarted = false;
}

Timer.prototype.reset = function () {
    this.pause();
    this.timeElapsed = 0;
}

// Timer creation example; the timer will be updated each 1000 milliseconds (= 1 second).
var timer = new Timer(1000);

您可以访问timer.timeElapsed,这样您就可以看到时间并进行操作。

请注意:由于Javascript是单线程的,因此无法保证计时器能够正常运行。实际上,在某些情况下它可能远离这个。