How to manage multiple timers in javascript?

advertisements

Below is the coding I use for one count up timer:

var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
function setTime()
{
    document.getElementById("seconds0").innerHTML=pad(++sec%60);
    document.getElementById("minutes0").innerHTML=pad(parseInt(sec/60,10));
}

var timer = setInterval(setTime, 1000);

If I have two timers, I write like this:

var sec = 0;
var sec1 = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
function setTime()
{
    document.getElementById("seconds0").innerHTML=pad(++sec%60);
    document.getElementById("minutes0").innerHTML=pad(parseInt(sec/60,10));
}
function setTime1()
{
    document.getElementById("seconds1").innerHTML=pad(++sec1%60);
    document.getElementById("minutes1").innerHTML=pad(parseInt(sec1/60,10));
}

var timer = setInterval(setTime, 1000);
var timer1 = setInterval(setTime1, 1000);

Actually the timer I use is to show waiting time of people. The number of people is a unknown variable. Means that it can be from 1 - 100. So, one people is one timer. Below is the function I written.

showWait = function(){
    var html = "";
    for (var i = 0; i < total; i++)
    {
            html += '<div id="numbers" class="col-sm-3 col-xs-6">'+i+'</div>';
            html += '<div id="qtime" class="col-sm-3 col-xs-6"></span><div><span class="glyphicon glyphicon-time"></span> Waiting</div><div id="waittime"><label id="minutes'+i+'">00</label>:<label id="seconds'+i+'">00</label></div></div>';
            html += '</div>';
    }
$('#waitnumber').html(html);
}

So, I don't think the way to create more timer is to keep repeating same function over and over again, right? It can't be if 100 people then there is 100 timers, right? Is there any simpler way to manage multiple timers?


i guess that every interval has 1000 ms waiting time, so you dont need multiple timers just one and in this one timer do what you need for every person

var sec = [time0, time1, time2 ....];
function pad ( val ) { return val > 9 ? val : "0" + val; }
function setTime()
{
    for(person = 0; person < numberOfPeople; person++)
    {
        document.getElementById("seconds" + person).innerHTML=pad(++sec[person]%60);
        document.getElementById("minutes" + person).innerHTML=pad(parseInt(sec[person]/60,10));
    }
}
var timer = setInterval(setTime, 1000);