Getting more than one javascript clock up at once?

C++, C#, Java, PHP, ect...
Post Reply
User avatar
Callan S.
Posts: 2042
Joined: Sun Jan 24, 2010 5:43 am

Getting more than one javascript clock up at once?

Post by Callan S. »

I'm not familiar with javascript - I've got some code I came across awhile ago, but it will only run one copy of the clock at a time, even if I include the code twice and make $clock_count different in each one. I'm likely to need several clocks at once. How can I do this? Thanks!

Code: Select all

<?php
if (isset($clock_count))
{
$display.="
        <script>
            var startTime = ".$clock_count.";
            var timer;
            window.onload = function() {
                //set the initial time
                var clock = document.getElementById('clock');
                clock.innerHTML = startTime;

                //start the timer
                timer = setInterval(function() {
                    //remove a second
                    startTime--;
                    //a little bit of trickery to make sure the 0th second is counted, but only 0 appears on the clock
                    if (startTime < 0) {
                        clock.innerHTML = 0;
                        //alert('The timer went off!');";

                        if (isset($clock_reload) && $clock_reload==true) $display.="location.reload();";

                        $display.="clearInterval(timer);
                    } else {
                        clock.innerHTML = startTime;
                    }
                }, 1000);
            };
        </script>

        <div id='clock'></div>
<?php
";
}
?>
User avatar
hallsofvallhalla
Site Admin
Posts: 12023
Joined: Wed Apr 22, 2009 11:29 pm

Re: Getting more than one javascript clock up at once?

Post by hallsofvallhalla »

make several instances of the clock function each attached to different divs. You could do it dynamically like

Psuedo code for setting up 100 clocks

Code: Select all

for(var i = 0; i < 100; i++)
{
document.getElementById("ClockContainer").innerHTML += "<div id="Clock" + i + "></div>"; 
StartClock("Clock" + i);
}

function StartClock(ThisClock)
{
run code for that div to start timer here
}
Post Reply

Return to “Coding”