JavaScript countdown cannot parse integer numbers

153 views Asked by At
<html>
    <body>
        <a id="haha">5</a>
        <script type="text/javascript">
            var myVar = setInterval(function(){apa()}, 1000);
            var f = 5;

            function apa() {
                document.getElementById("haha").innerHTML = f;
                f--;
                apa();
            }       
        </script>
    </body>
</html>

I tried to make countdown with timer and decrements, but the output come out not as integer (5, 4, 3, 2, 1,......) but stuffs like -336048 etc instead. How do I fix this?

2

There are 2 answers

0
Arun P Johny On BEST ANSWER

Should not call apa() inside apa it creates a infinite recursion. The setInterval() will call apa in 1 sec intervals so no need to call it again.

//also there is no need to use a anonymous function you can just say
//var myVar = setInterval(apa, 1000);
var myVar = setInterval(function () { 
    apa()
}, 1000);
var f = 5;

function apa() {
    document.getElementById("haha").innerHTML = f;
    f--;
}

var myVar = setInterval(apa, 1000); //just pass the apa reference to setInterval
var f = 5;

function apa() {
  document.getElementById("haha").innerHTML = f;
  f--;
}
<a id="haha">5</a>

0
Roli Agrawal On

You can try this . this will count only(5 4 3 2 1)

var myVar=setInterval(function(){if(f>0) apa()},1000);
        var f=5;
         function apa() 
        {
            document.getElementById("haha").innerHTML = f;
            f--;
        }