views:

84

answers:

5

Let me explain what I'm trying to do.

I want to make a simple box which counts down numbers at intervals I specify.

For example, I'd like to set it to start at 150, and then I want to set it to drop by 15 every 30 seconds.

Is this possible with AJAX/Javascript? If so, could someone point me in the right direction?

Would really appreciate any help on this script, been Googling for hours now! :(

Cheers

Kieran

+1  A: 

Have a look at the setTimeout or setInterval methods, they allow you to execute a function after a specified number of milliseconds (1000ms = 1second). Use that, to call a function that keeps dropping the number and writes it to a HTML element to the user can see it.

CharlesLeaf
+1  A: 

this isn't tested, but i hope it shows you the way to go.

var start = 150;
var drop = 15;
var interval = 30;

function countdown(){
    document.getElementById('mybox').innerHTML = start;
    start-=drop;
    window.setTimeout("countdown",interval*1000);
}

countdown();
oezi
Thanks for this, I'll attempt to make this work! All we need is a simple solution.
kieran
You just need a stop somewhere, and you should use setInterval to avoid drifting away.
Alsciende
A: 

You may use jQuery to do that, see http://keith-wood.name/countdown.html -> tab Callbacks

Radek Šimko
JQuery is a lot of overhead for a simple countdown if its not already being used in the project.
Neil Aitken
You're absolutly right, that is why I wrote "you -MAY- use" ;-)The advantages and disadvantages of this solution are for the special article...
Radek Šimko
A: 

Keep in mind that 30 seconds in my browser are not necessarily equal to 30 seconds in your browser. It depends on the workload of the browser. The time difference is minor for a short time but can increase over a long time. The times will drift apart. If the times must not be equal (or nearly equal) between two visitors than such simple solution should be fine.

We had once a problem to introduce a live clock / countdown in one of our projects. We build a script with javascript, ajax and PHP for clock synchronisation (server time was timeserver).

Julian
A: 

You should use setInterval / clearInterval which is made for this kind of tasks:

function cooldown(element, start, stop, step, delay) {
    var current = start;
    element.innerHTML = current;
    var timer = setInterval(function () {
        current -= step;
        if(current < stop) current=stop;
        element.innerHTML = current;
        if(current == stop) clearInterval(timer);
    }, delay*1000);
}

Demonstrated here : http://jsfiddle.net/PCMHn/

Alsciende