Ricky T
Ricky T

Reputation: 243

How to set javascript timer back to ZERO upon page reload

I am using this timer with a page loader. The problem is if a page finishes loading before the timer is up, then the next time you load the page, the timer starts where it left off the last time the page executed. I need to make sure the count variable is set to zero on page re-load. Thanks in advance

<script>
    var myVar=setInterval(function(){myTimer()},1);
    var count = 0;
    function myTimer() {
        if(count < 100) {
        $('.progress').css('width', count + "%");
        count += 0.025;
        document.getElementById("demo").innerHTML = Math.round(count) +"%";
        // code to do when loading
    } else if(count > 100) {
        // code to do after loading
        count = 0;
        }
    }
</script>

Upvotes: 0

Views: 610

Answers (1)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

You can wrap your code into a function which will reset the counter and start it again:

<script>
    var myVar;
    var count;
    function restartTimer() {
        count = 0;
        clearInterval(myVar);
        myVar = setInterval(function(){ myTimer() }, 1);
    }
    function myTimer() {
        if(count < 100) {
            $('.progress').css('width', count + "%");
            count += 0.025;
            document.getElementById("demo").innerHTML = Math.round(count) +"%";
            // code to do when loading
        } else if(count > 100) {
            // code to do after loading
            count = 0;
        }
    }
</script>

And now you just need to call restartTimer function wherever you want:

resetTimer();

In your case, you need to call it before every call to PHP page.

Upvotes: 1

Related Questions