Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

html - Having multiple countdown timer events intervals in javascript

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...