简体   繁体   English

按下返回按钮后刷新JS coutndown计时器吗?

[英]Refreshing a JS coutndown timer after pressing the back button?

My server runs some database maintenance scripts each night at midnight. 我的服务器每晚晚上12点运行一些数据库维护脚本。 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. 这是通过将预处理(php)期间的服务器时间导出到JS变量,并在一个简单的循环显示例程中循环秒数来完成的。

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. 您可以使用Ajax调用在客户端与服务器刷新(同步)时间。 All you need to do is to identify the best time interval after which you will send Ajax call to sync time. 您需要做的就是确定最佳时间间隔,在此之后您将发送Ajax调用以同步时间。

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 每次用户加载页面时,它都会获得准确的时间(从此开始),而不必持续向服务器发送呼叫

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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