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?

3
  • see this post stackoverflow.com/questions/20618355/… Commented Jul 30, 2020 at 15:17
  • Maybe setInterval("countDown()", 1000) should be setInterval(countDown, 1000)? Commented Jul 30, 2020 at 15:22
  • Make ncount public. Commented Jul 30, 2020 at 15:33

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.