A simple count down timer?

Why isn’t the setTimeout working?
When I ran it, it displays all the numbers instantly.
And, how do I do a clear screen before printing, so it doesn’t append the results?


cd = {
    countDown: function(start) {
        var i = 0;
        while (i<start) {
          setTimeout(this.update(start), 1000);
          start--;
        }

    },
    update: function(start) {
      document.clear();
      document.write(start);
    }
}
cd.countDown(10);


Because you are executing the update function and assigning the returned value, which is undefined, to the timeout.
Instead of that, you want to assign a function to the timeout instead.


setTimeout([color="green"]function () {[/color]
    this.update(start), 1000);
[color="green"]}[/color]

The problem there now though is that the this keyword no longer refers to the same object, which is why we assign this to that, so that we can then use this.


[color="green"]var that = this;[/color]
while (...) {
    setTimeout(function () {
    [color="green"]that[/color].update(start), 1000);
}

The i variable doesn’t ever change from 0, so get rid of the i variable and just use 0 instead.


[s][color="red"]var i = 0;[/color][/s]
while ([color="green"]start > 0[/color]) {

Because the scripting does not stop or pause with the setTimeout, we need to have the end of that update function call the countdown function again.
That also means that the while statement must become an if statement, and the decrement needs to be moved elsewhere.


countDown: function(start) {
    ...
    [s][color="red"]while[/color][/s][color="green"]if[/color] (start > 0) {
        ...
        [s][color="red"]start--;[/color][/s]
    }
},
update: function(start) {
    ...
    [color="green"]start--;
    this.countDown(start);[/color]
}
&#8203;

Now the countdown occur at an appropriate delay.

There is no “clear screen” command, but instead you can set the innerHTML of the body, which results in everything being replaced.

update: function(start) {
      [color="green"]document.body.innerHTML = start;[/color]
      start--;
      this.countDown(start);
    }
}

that is awesome.
finally it works http://jsfiddle.net/99QKp/3/
thanks :slight_smile: