倒数计时器的setInterval问题-多次运行?

时间:2020-04-06 21:08:30

标签: javascript

我正在构建一个简单的问答游戏作为学习JS的方式。游戏中有一个倒数计时器,为45秒。但是我创建了一个延迟(5、10、15秒),以允许用户使用string.length函数读取问题。一切正常,但是在几个问题之后,计时器开始变得有趣起来,好像有多个计时器在同时运行,并且时间下降快了2倍3倍。

    // Question countdown timer function

function timerStart() {
    timeleft = 45;
    downloadTimer = setInterval(function() {
        if (timeleft <= 0) {
            clearInterval(downloadTimer);
            timeOut();
        } else {
            $('#countdown').html(timeleft + ' seconds remaining');
        }
        timeleft -= 1;
    }, 1000);
}

function resetTimer() {
    clearInterval(downloadTimer);
    $('#countdown').empty();
}

// Function to delay the timer based on the length of the question

function delay() {
    var t = calculateDelay(questionLength) * 1000;
    console.log('Time: ' + t);
    setTimeout(function() {
        timerStart();
    }, t);
}

// Function to check selected answer

function selected(a) {
    $('#' + a).addClass('selected-answer');
    if (a == correctAnswer) {
        alert('You guessed it right!');
        // $("#correct").html("You guess it right");
        step = step + 1;
        resetTimer(); // This suppose to reset my timer but it doesn't after few answers
        startGame(); // This function picks another question and displays on screen and calls delay() to start another timer
    } else if (timeleft <= 0) {
        timeOut();
    } else {
        wrongAnswer();
    }
}

0 个答案:

没有答案
相关问题