Having multiple countdown timer events intervals i

2019-06-02 21:59发布

问题:

I am trying to create a multiple countdown timers using javascript. Facing issues with displaying the time and setInterval cleartInterval events of javascript. My code is on jsfiddle: here

Javascript:

function secondPassed(row, secs) {
    var seconds = secs;
    var minutes = Math.round((seconds - 30)/60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds;  
    }
    document.getElementById('countdown'+row).innerHTML = minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(countdownTimer[row]);
        document.getElementById('countdown'+row).innerHTML = "Buzz Buzz";
    } else {
        seconds--;
    }
}

var countdownTimer = [];

function timer(row, min) { 
    var seconds = min * 60;
    countdownTimer[row] = setInterval('secondPassed('+row+','+seconds+')', 1000);
}


timer(1, 3);
timer(2, 2);
timer(3, 5);

HTML: Timer 1: <span id="countdown1" class="timer"></span> <br/> Timer 2: <span id="countdown2" class="timer"></span> <br/> Timer 3: <span id="countdown3" class="timer"></span>

回答1:

There are a couple problems here.

First, the syntax for setting a timer function with parameters is wrong. See Pass parameters in setInterval function.

Second, you need to store the remaining seconds for each timer somewhere.

var timerData = [];

function secondPassed(row) {
    var seconds = timerData[row].remaining;
    var minutes = Math.round((seconds - 30) / 60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds;
    }
    document.getElementById('countdown' + row).innerHTML = minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(timerData[row].timerId);
        document.getElementById('countdown' + row).innerHTML = "Buzz Buzz";
    } else {
        seconds--;
    }
    timerData[row].remaining = seconds;
}

function timer(row, min) {
    timerData[row] = {
        remaining: min * 60,
        timerId: setInterval(function () { secondPassed(row); }, 1000)
    };
}

timer(1, 3);
timer(2, 2);
timer(3, 5);

Working fiddle: http://jsfiddle.net/835xehna/4/