1

I have started learning JavaScript and I thought of trying a simple count down timer but I can't figure out.

function countdown() {
  var count1 = 10;
  while (count1 >= 0) {
    setTimeout(function() {
      document.getElementById("main").innerHTML = count1;
    }, 1000);
    count1--;
  }
}
<p id="main" onload="countdown()"></p>

The page just stops/hangs. What is wrong with it?

John Bupit
  • 10,406
  • 8
  • 39
  • 75
ssh
  • 491
  • 1
  • 8
  • 19
  • use `setInterval(function(){ ... })` for this – Dev Man Feb 14 '17 at 06:22
  • I don't think `onLoad` on the `p` element will do anything. I don't think your page is stopping or hanging; it's not doing anything to start with. Try adding `document.addEventListener('DOMContentLoaded', countdown);`, then you can debug the rest of your logic. –  Feb 14 '17 at 06:51
  • Possible duplicate of [Code for a simple JavaScript countdown timer?](http://stackoverflow.com/questions/1191865/code-for-a-simple-javascript-countdown-timer) – Divyesh Kanzariya Feb 14 '17 at 07:02

3 Answers3

2

Use setInterval for timers, then clear it when the countdown reaches to 0. Make sure to use an immediately invoked anonymous function or execute the named function immediately upon defining. Your function will not execute otherwise, so no timer for you.

function countdown() {
  var count1 = 10;
  var myTimer = setInterval(function() {
    document.getElementById("main").innerHTML = count1;
    count1--;
    if (count1 == 0) {
      clearInterval(myTimer);
    }
  }, 1000);
}
countdown();
<div id="main"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Abana Clara
  • 4,602
  • 3
  • 18
  • 31
0

You should use setInterval instead, so it gets called regulary, and counting down (decreading the counter) should happen within the function called by setInterval. You can omit the loop then, just call clearInterval when then counter reaches 0.

Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
0

setTimeout executes the function only once. Using setInterval can help here.

But another point to note is about scoping of variables here. While the setTimeOut waits for 1 sec, the while loop will keep executing along, changing the value of count1.

The value of count1 will be -1 all the time. Using an Immediately Invoked Function Expression (IIFE) is whats needed.

function countdown()
{
    var count1 = 10;
    while( count1 >= 0) {
      var myTimer = setInterval((function() {
        console.log(count1);
      }(count1)), 1000);
      count1 = count1 - 1;
    }
}
countdown()

Jsfiddle

Hozefa
  • 1,676
  • 6
  • 22
  • 34