简体   繁体   中英

Refreshing a JS coutndown timer after pressing the back button?

My server runs some database maintenance scripts each night at midnight. In order to prevent interference from the end user all sessions are terminated a few minutes before execution. So that the user isn't rudely interrupted in the middle of doing something important, a countdown timer shows the remaining time. This is done by exporting the server time during preprocessing (php) to a JS variable and cycling down the seconds in a simple looping display routine.

This works as intended most of the time, however, if the user navigates to the page by pressing the back button the time displayed will be out of sync. Is there a way I can make sure the script is getting the most current server time each time the page is viewed, even when being viewed after having pressed the back button?

It's very simple...

var seconds = <?php echo $time_left; ?>;
function display_timer ()
{
    seconds--;
    minutes = parseInt((seconds / 60) % 60);
    hours = parseInt(seconds / 3600);

    ds = seconds % 60;
    ds = ds > 9 ? ds.toString() : '0' + ds.toString();
    dm = minutes > 9 ? minutes.toString() : '0' + minutes.toString();
    dh = hours > 9 ? hours.toString() : '0' + hours.toString();

    document.getElementById('countdown').innerHTML = 'Time left: ' + dh + ':' + dm + ':' + ds;

    if (seconds)
    {
        setTimeout("display_timer()", 1000);
    }
}

display_timer();

You can use Ajax call to refresh (Sync) time at client side with server. All you need to do is to identify the best time interval after which you will send Ajax call to sync time.

Ummar's suggestion would work. Maybe for something a little more basic: If the time remaining is calculated on the server side, then how about you pass the time remaining through to client side, then start the count-down timer from there. Everytime the user loads the page it will get an accurate time, to start from, then doesnt have to continually send calls to the server

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