javascript 刷新页面时不会重置的倒数计时器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13412153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:41:21  来源:igfitidea点击:

Countdown Timer that doesn't reset when you refresh the page?

javascriptjqueryhtmlcss

提问by FunnyFalcon

I Need to have a code for the timer that doesn't reset the countdown timer even you refresh the page.

我需要一个计时器代码,即使您刷新页面也不会重置倒数计时器。

I saw sample code at keith wood plug in, but don't know how to implement this in my html file.here's the link :

我在keith wood plug in看到了示例代码,但不知道如何在我的html 文件中实现它这是链接:

http://keith-wood.name/countdown.html

http://keith-wood.name/countdown.html

I hope somebody could help me! thanks! :)

我希望有人可以帮助我!谢谢!:)

I just need Hour, Minutes and Secondsto show. And after the Time given, there is a prompt box that will show "Time is up! ". This one is for the online exam we are developing. Thank you so Much! :)

我只需要显示小时、分钟和秒。并且在给出的时间之后,有一个提示框会显示“时间到了!”。这是我们正在开发的在线考试。太感谢了!:)

回答by Zze

If you know that the user will have local cache enabled and able to store data, you could save 2 values to localStorage, 1 for the currentTimeand 1 for the targetTime. Then you compare the 2 in an interval and if currentTime > targetTime, display your message.

如果您知道用户将启用本地缓存并能够存储数据,您可以将 2 个值保存到localStorage,1 个用于currentTime,1 个用于targetTime。然后您在一个时间间隔内比较 2,如果currentTime > targetTime,则显示您的消息。

Also bind to the onbeforeunloadevent and save the new currentTime back into localStorage. This will give you the persisted countdown you are seeking.

还绑定到onbeforeunload事件并将新的 currentTime 保存回localStorage. 这将为您提供您正在寻找的持续倒计时。

Here is an example of how you can do this:

以下是如何执行此操作的示例:

var interval;
let minutes = 1;
let currentTime = localStorage.getItem('currentTime');
let targetTime = localStorage.getItem('targetTime');
if (targetTime == null && currentTime == null) {
  currentTime = new Date();
  targetTime = new Date(currentTime.getTime() + (minutes * 60000));
  localStorage.setItem('currentTime', currentTime);
  localStorage.setItem('targetTime', targetTime);
}
else{
  currentTime = new Date(currentTime);
  targetTime = new Date(targetTime);
}

if(!checkComplete()){
  interval = setInterval(checkComplete, 1000);
}

function checkComplete() {
  if (currentTime > targetTime) {
    clearInterval(interval);
    alert("Time is up");
  } else {
    currentTime = new Date();
    document.write(
     "\n <font color=\"white\"> Seconds Remaining:" + ((targetTime - currentTime) / 1000) + "</font>");
  }
}

document.onbeforeunload = function(){
  localStorage.setItem('currentTime', currentTime);
}

Note that I would've made a snippet however stackoverflow and other online IDE's are complaining about security breaches. Note that this is perfectly valid and does not breach any security. Save it as a .jsand run.

请注意,我会制作一个片段,但是 stackoverflow 和其他在线 IDE 抱怨安全漏洞。请注意,这是完全有效的并且不会破坏任何安全性。将其另存为 a.js并运行。

To start the "countdown" again, invoke localStorage.clear().

要再次开始“倒计时”,请调用localStorage.clear().

回答by pala?н

  1. Include the jQuery library in the head section of your page.
  2. Download and include the jQuery Countdown CSS and JavaScript in the head section of your page. Alternately, you can use the minimised version jquery.countdown.min.js (13.5K vs 31.4K, 4.4K when zipped).
  3. Connect the countdown functionality to your divs.
  1. 在页面的头部部分包含 jQuery 库。
  2. 下载 jQuery Countdown CSS 和 JavaScript 并将其包含在页面的头部部分。或者,您可以使用最小化版本 jquery.countdown.min.js(13.5K 对 31.4K,压缩时为 4.4K)。
  3. 将倒计时功能连接到您的 div。

So, your final code will be:

因此,您的最终代码将是:

<html>
<head>
    <title>jQuery Countdown</title>
    <style type="text/css">@import "jquery.countdown.css";</style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.countdown.js"></script>
    <script type="text/javascript">
        $(function () {
        var year = new Date();
        year = new Date(year.getFullYear(), 11 - 1, 20);
        $('#dvCountDown').countdown({until: year, format: 'HMS'});
            $('#year').text(austDay.getFullYear());
        });
    </script>
</head>
<body>
<h1>jQuery Countdown Basics</h1>
<p>Counting down to 20 November <span id="year">2012</span>.</p>
<div id="dvCountDown"></div>

</body>
</html>

Hope this helps!

希望这可以帮助!

回答by Jeremy John

If you want to use that script then you'll have to count by date and not a custom countdown value in order for it not to get reset on page refresh: http://jsfiddle.net/qWERa/1/

如果您想使用该脚本,则必须按日期而不是自定义倒计时值进行计数,以免在页面刷新时重置:http: //jsfiddle.net/qWERa/1/

//Custom countdown value starting on page load
$('#CountdownbyValue').countdown({until: '+0h +0m +8s', format: 'HMS',onExpiry: liftOff,});

//Countdown by Date
$('#CountdownbyDate').countdown({until: new Date(2012, 11-1, 17, 10, 10, 10), format: 'HMS',onExpiry: liftOff,});

//Time is up dialog!
function liftOff() {
    alert('Time is up!');
}

Full Code:

完整代码:

<html>
<head>
<title>Demo</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script> 
<script type='text/javascript' src='http://keith-wood.name/js/jquery.countdown.js'></script>
<link rel="stylesheet" type="text/css" href="http://keith-wood.name/css/jquery.countdown.css">
<script type='text/javascript'> 
$(window).load(function(){
//Starts from time of page load
$('#CountdownbyValue').countdown({until: '+0h +0m +8s', format: 'HMS',onExpiry: liftOff,});

//Counts by Date
$('#CountdownbyDate').countdown({until: new Date(2012, 11-1, 17, 10, 10, 10), format: 'HMS',onExpiry: liftOff,});

//Time is up!
function liftOff() { 
    alert('Time is up!'); 
} 
});
</script>
</head>
<body>
<div id="CountdownbyValue"></div>
<div id="CountdownbyDate"></div>
</body>
</html>

Your can also try:

您也可以尝试:

window.onbeforeunload = function() {
    return "Are you sure you want to quit this exam?";
}

I suggest you take a look at this Countdown timer with cookies

我建议你看看这个带有 cookie 的倒数计时器