mardi 12 décembre 2017

How to create a counter that increments by 1 every 1-8 seconds(random)

So I think I'm close, but what I've written begins to increment by larger values, and at an increasing speed the longer it runs. I assume this is an issue with the interval not being properly cleared. Please assist in anyway possible.

<html>
    <head>
        <script type="text/javascript">

            function setTimer(){
                var timer = (((Math.floor(Math.random() * 6))+1)*1000);
                clearInterval(interval);
                var interval = setInterval(updateCounter, timer);
            }

            function updateCounter(){
                var count = parseInt(document.getElementById("counter").innerHTML);
                count++;
                document.getElementById("counter").innerHTML = count;
                setTimer();
            }

        </script>
    </head> 

    <body style="margin:5%;" onload="setTimer()">
        <div id="counter">1</div>
    </body>
</html>




Aucun commentaire:

Enregistrer un commentaire