简体   繁体   English

如何停止在JavaScript中刷新倒数计时器

[英]How to stop refreshing countdown timer in javascript

`<script type="text/javascript" src="jquery-1.6.2.min.js"></script>

<h1 align="center" style="color:green">A countdown timer in jquery</h1>

<h3 style="color:#FF0000" align="center"> You will be logged out in : <span id='timer'></span> </h3>

<script>
//define your time in second
    var c=60;
    var t;
    timedCount();

    function timedCount()
    {

        var hours = parseInt( c / 3600 ) % 24;
        var minutes = parseInt( c / 60 ) % 60;
        var seconds = c % 60;

        var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);


        $('#timer').html(result);
        if(c == 0 )
        {
            //setConfirmUnload(false);
            //$("#quiz_form").submit();
            window.location="result.php";
        }
        c = c - 1;
        t = setTimeout(function()
        {
         timedCount()
        },
        1000);
    }
</script>` 

I have this script that does work fine but ,a small trouble it is causing that when i refresh the page the timer resets. 我的脚本运行正常,但是有一个小麻烦,那就是当我刷新页面时计时器重置。 I want that it does not reset on refreshing the page. 我希望它不会在刷新页面时重置。

Check whether or not the user is already counting down (ie whether a target time is stored, and in future), if not store the target time. 如果没有存储目标时间,请检查用户是否已经在递减计数(即是否存储了目标时间,以及将来是否已存储)。 Then provide c as the difference between the current time and the stored target time. 然后提供c作为当前时间与存储的目标时间之间的差。 You can use 您可以使用

  • Session storage, and render c directly into the webpage 会话存储,并将c直接呈现到网页中
  • Session storage, and ask for c from the server using AJAX 会话存储,并使用AJAX向服务器请求c
  • document.cookie or window.localStorage , so that server does not need to get involved. document.cookiewindow.localStorage ,因此服务器不需要参与。

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

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