tags:

views:

159

answers:

4

I have from the backend a time on the format 00:12:54 and I display it to the screen. But, I would like to have this time to continue to go down. I have though to create a variable in javascript that will old the time and with setTimeout to loop to display with document.getElementById the new value. I think it can be problematic if I have many time to go down in same time. I might require an array?

How would you do that? If I have no other suggestion, I will try my way, but I am curious to know if it does have a more secure way to do it.

+4  A: 

Do you know jQuery Framework? It's a Javascript framework that have a lot of utilities methods and functions that let you do Javascript stuff more easily.

Here is a count down plugin (haven't tested it).

I suggest you to download JQuery than download the plugin . Check the sample of code from the "relative" tab on the website. You can have something like :

 $('#until2d4h').countdown({until: '+12M +54S'});

*The only drawback with what I suggest you is that you will require 2 .js to be added. Try to add them only when needed and you will be find.

Daok
Have not used this one, but have found other plugins by Keith Wood to be very reliable
seanb
Good one but do not want to use all those .js file.
SexyBunny
+1  A: 

You won't like the taste of this one, but it'll do you good:

Google for 'javascript timer' and get your hands dirty reading through the various examples and tutorials returned by that search.

You'll learn a lot more than just how to write a count-down timer. :-)

Good luck!

Már Örlygsson
+2  A: 

General algorithm:

  1. Read time from server.
  2. Read the current time.
  3. Call a function.
  4. In your function, read the current time, get the delta from the initial time you read in step 2.
  5. Subtract the delta from the initial time you read from the server in step 1 and display the remainder.
  6. The function should call window.setTimeout to call itself in 1000ms (or adjust according to time elapsed within the function), if you want to continue counting down.

Here's a rough cut:

window.onload = function () {
    var countdown_start_in_ms = 6000; // from server

    function tick() {
        var now = new Date().getTime();
        var disp = start - now;

        if (disp < 0) {
            disp = 0;
        }

        var el = document.getElementById("countdown");

        el.innerHTML =
            // quick hack to format time
            /(\d\d:\d\d:\d\d) ...$/.exec(new Date(disp).toUTCString())[1];

        if (disp > 1000) {
            var elapsed = new Date().getTime() - now;
            window.setTimeout(tick, 1000 - elapsed);
        } else {
            // stop countdown and set color to light grey
            el.style.color = "#ccc";
        }
    }

    var start = new Date().getTime() + countdown_start_in_ms;
    tick();
}
Ates Goral
A: 
Eugene Lazutkin