2

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>
2
  • what actually you want here? Commented Aug 8, 2014 at 14:44
  • @Mritunjay I am trying to have multiple countdown timers with just one function. Dynamic basically. Commented Aug 8, 2014 at 14:52

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, for pointing out my faults. Works like a charm now. You rock.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.