2

My JavaScript timer is working bizarrely: it goes 3-2 and then abruptly it finishes (without going through step 1 and 0). Here is the code:

var count = 3;
function countDown() {
  document.getElementById("count").innerHTML = count;
  if (count > 0) {
    count--
  }
  else {
    clearInterval(ncount);
    document.getElementById("count").style.display = "none"
  }
  var ncount = setInterval("countDown()", 1000);
}
<form id="askName">
  <label> Enter your username: </label>
  <input id="input" type="text" required maxlength="10">
  <button type="button" onclick="countDown()"> Submit </button>
</form>
<h2 id="count"> </h2>

Why does this occur?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80

2 Answers2

2

The issue is that your setInterval is calling your function that spawns another setInterval, which causes the count to be decremented faster. You can use a inner function to avoid this issue.

var count = 3;
function countDown() {
   function helper(){
    document.getElementById("count").innerHTML = count;
    if (count > 0) {
      count--;
    }  else {
      clearInterval(ncount);
      document.getElementById("count").style.display = "none"
    }
  }
  var ncount = setInterval(helper, 1000);
}
<form id="askName">
  <label> Enter your username: </label>
  <input id="input" type="text" required maxlength="10">
  <button type="button" onclick="countDown()"> Submit </button>
</form>
<h2 id="count"> </h2>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

This Should work fine. I tried Changing the setInterval Time

var count = 3;
    function countDown() {
        function helper() {
            document.getElementById("count").innerHTML = count;
            if (count > 0) {
                count--;
             } else {
                clearInterval(ncount);
                document.getElementById("count").style.display = "none";
        }
      }
      var ncount = setInterval(helper, 1020);
    }
<form id="askName">
  <label> Enter your username: </label>
  <input id="input" type="text" required maxlength="10">
  <button type="button" onclick="countDown()"> Submit </button>
</form>
<h2 id="count"> </h2>
Jakub Kriz
  • 1,501
  • 2
  • 21
  • 29