Search code examples
javascripttimercountdown

JavaScript countdown cannot parse integer numbers


<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?


Solution

  • 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>