简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM