Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Simple Countdown with for loop

Tags:

javascript

Hi I'm trying to create a simple countdown.
Here is my code but it's not working.
Can you help me find the problem?

function count() {
    for (var cc=20,cc > 0,cc--) {
        document.getElementById("cco").innerHTML=cc;
    }
}
count();
like image 730
user1599537 Avatar asked Dec 01 '25 11:12

user1599537


2 Answers

You're using commas instead of semicolons.

for (var cc=20,cc > 0,cc--)

should be

for (var cc=20;cc > 0;cc--)

However, this probably won't do what you think it will, as the loop will count all the way to 0 immediately (so the user won't even see the countdown). I'm guessing you wanted something like:

var cc = 20;

var interval = setInterval(function()
{
    document.getElementById("cco").innerHTML = -- cc;

    if (cc == 0)
        clearInterval(interval);

}, 1000);

See setInterval and clearInterval for more information.

like image 135
James McLaughlin Avatar answered Dec 06 '25 01:12

James McLaughlin


There are (at least) two mistakes.

The first is syntactical: In a for loop the parameters are separated by ; and not by ,. Syntactic correct code would look like this:

function count() {
  for (var cc=20;cc > 0;cc--) {
    document.getElementById("cco").innerHTML=cc;
 }
}

Second, you do not have a countdown, but override the very same element over and over again, without any time for the user to see the result.

A better approach would be to use setTimeout() here, which could look like this:

var cc = 20;
function count() {
  document.getElementById("cco").innerHTML=cc;
  if ( cc > 0 ) {
    setTimeout( count, 1000 );
  }
}

setTimeout( count, 1000 );

The setTimeout() approach leaves some time for the browser to actually render your modifications (and for the user to see it).

like image 35
Sirko Avatar answered Dec 06 '25 00:12

Sirko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!