1

I have a 10 minute countdown and I need it to keep counting even if page gets reloaded or user goes to another page. Also I need it to execute a function when counted to 0.

I have some code that sets 10 minute countdown

<div id="clockdiv"></div>
<script>
    var time_in_minutes = 10;
    var current_time = Date.parse(new Date());
    var deadline = new Date(current_time + time_in_minutes*60*1000);
    var finishTime;

    function time_remaining(endtime){
        var t = Date.parse(endtime) - Date.parse(new Date());
        var seconds = Math.floor( (t/1000) % 60 );
        var minutes = Math.floor( (t/1000/60) % 60 );
        var hours = Math.floor( (t/(1000*60*60)) % 24 );
        var days = Math.floor( t/(1000*60*60*24) );
        return {'total':t, 'days':days, 'hours':hours, 'minutes':minutes, 'seconds':seconds};
    }

    function run_clock(id,endtime){
        var clock = document.getElementById(id);
        function update_clock(){
            var t = time_remaining(endtime);
            clock.innerHTML = 'minutes: '+t.minutes+'<br>seconds: '+t.seconds;
            if(t.total<=0){ clearInterval(timeinterval); }
            if(t.total<=0){

                console.log('execute function');
            }
        }
        update_clock(); // run function once at first to avoid delay
        var timeinterval = setInterval(update_clock,1000);
    }
    run_clock('clockdiv',deadline);

</script>

So I got it to the point where it counts to 0 and says "execute function" in console.log but it gets reset every time page reloads.

My desired result would be that the counter keeps counting even if page gets reloaded.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Davis
  • 361
  • 1
  • 5
  • 19
  • Javascript variables are not persistent. To make them persistent you need to store them locally with help of Cookies or LocalStorage. – Markus Zeller Aug 15 '19 at 09:23

0 Answers0