计时器在第二轮开始加速

时间:2014-01-28 11:07:09

标签: javascript jquery timer

我借了一些JS代码来帮我创建一个65秒的计时器。我的JS知识是基本的,但我设法修改脚本以我想要的方式工作。但是,当我点击play按钮时,计时器会从第二轮开始加速。

HTML:

<div id="rightCol">
        <span id="countdown" class="timer">Timer About to Start! </span>
        <div>
            <input type="button" value="Play" id="play">
        </div>
    </div>

JS:

var seconds = 65;

function secondPassed() {
    var minutes = Math.round((seconds - 30)/60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds;  
    }
    document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(countdownTimer);
        document.getElementById('countdown').innerHTML = "Time's Up!";
            document.getElementById("passage_text").disabled = true;

    } else {
        seconds--;
    }
}
 
var countdownTimer = setInterval('secondPassed()', 1000);

$("#play").click(function(){

    seconds = 65;
    var countdownTimer = setInterval('secondPassed()', 1000);

    $('#passage_text').attr('disabled', false).focus();
    $("#passage_text").val('');



});

我读了一些类似于我Count down timer speeds up的其他答案,但我不完全理解secondPassed()函数如何解决它。

1 个答案:

答案 0 :(得分:1)

您还需要清除play功能的间隔,并使countdownTimer全局。最好将函数处理程序传递给setInterval而不是字符串,因为这将作为eval函数使用,不建议使用

var seconds = 65;
var countdownTimer = null; // make it global

function secondPassed() {
    var minutes = Math.round((seconds - 30)/60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds;  
    }
    document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(countdownTimer);
        document.getElementById('countdown').innerHTML = "Time's Up!";
            document.getElementById("passage_text").disabled = true;

    } else {
        seconds--;
    }
}

countdownTimer = setInterval(secondPassed, 1000); // removed var and passing handler instead of string.

$("#play").click(function(){

    seconds = 65;
    clearInterval(countdownTimer); // clear interval
    countdownTimer = setInterval(secondPassed, 1000); // removed var to use global countdownTimer variable

    $('#passage_text').attr('disabled', false).focus();
    $("#passage_text").val('');
});

参见我上面的JS评论