Count for x to 0 in Javascript?

I have a time in the backend in the 00:12:54 format and I am displaying it on the screen. But I would like to keep going down this time. I have, though, to create a variable in javascript to be the old one, and using setTimeout

in a loop to display with document.getElementById the new value. I think it can be problematic if I have a lot of time to go down at the same time. An array might be required?

How do you do it? If I have no other suggestion, I'll try my way, but I'm curious to see if there is a safer way to do this.

0


source to share


4 answers


General algorithm:

  • Server read time.
  • Read the current time.
  • Function call.
  • In your function, read the current time, get the delta from the start time you read in step 2.
  • Subtract the delta from the starting time that you read from the server in step 1 and display the remainder.
  • The function must call window.setTimeout

    to call itself in 1000ms (or adjust according to the time elapsed within the function) if you want to continue counting.


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();
}

      

+2


source


Do you know the jQuery Framework? It is a Javascript framework that has many utility methods and functions that enable you to do Javascript things more easily.

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

I suggest you download jQuery than download the plugin . Check out the sample code from the "relative" tab on the website. You might have something like:



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

      

* The only drawback I'm suggesting is that you need to add 2.js. Try to add them only when needed and you will find.

+4


source


You won't like the taste of this, but it will benefit you:

Google for ' javascript timer ' and get your dirty data back with various examples and tutorials returned by this search.

You will learn a lot more than just writing a countdown timer. :-)

Good luck!

+1


source


Take a look at Join Hands and set your own time. and check its code. Although written with Dojo, the "clock" portion has simple JavaScript. In your case, the only difference is how to advance the counter - decrement, not increment it.

0


source







All Articles