我创建了自己的倒计时,似乎我缺少一部分,每当刷新页面时,它也会刷新计时器本身。我希望通过该脚本实现最佳性能,那么如何使其无限循环?
以下是代码:
function startGRBTimer(duration, display) {
var timer = duration,
hours, minutes, seconds;
setInterval(function() {
days = parseInt(timer / (24 * 60 * 60), 10);
hours = parseInt(timer % (24 * 60 * 60) / (60 * 60), 10);
minutes = parseInt(timer % (60 * 60) / 60, 10);
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = days + "d" + " " + hours + "h " + minutes + "m " + seconds + "s";
--timer;
if (timer <= 0) {
timer = duration;
}
}, 1000);
}
var display = document.querySelector("#grb");
startGRBTimer(60, display);
答案 0 :(得分:0)
这只是这段代码的工作方式,没有错。每次刷新页面时,脚本都会重新运行,并且在每次加载页面时都会创建private void Button_Click(object sender, RoutedEventArgs e)
{
var url = (sender as Button)?.Tag;
}
。
您应该首先考虑创建,然后将变量存储到用户的本地存储中,并让程序从该变量(或数组)中读取信息。
答案 1 :(得分:0)
您需要独立于Web应用程序执行某些工作,并且能够在页面刷新后继续工作,对吗?
ServiceWorkers很可能对您有用。
答案 2 :(得分:0)
对于这种情况,我们可以“滥用” window.name
(请参见文档链接),如以下示例所示。或者,您可以使用 localStorage
,但这不适用于本地文件(file:///...
)。正因为如此,window.name
也越来越好。
解决方案
function startGRBTimer(duration, display)
{
var timer = window.name == '' ? duration : window.name,
hours, minutes, seconds;
setInterval(function()
{
days = parseInt(timer / (24 * 60 * 60), 10);
hours = parseInt(timer % (24 * 60 * 60) / (60 * 60), 10);
minutes = parseInt(timer % (60 * 60) / 60, 10);
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = days + "d" + " " + hours + "h " + minutes + "m " + seconds + "s";
--timer;
if(timer <= 0)
{
timer = duration;
}
window.name = timer;
}, 1000);
}
var display = document.querySelector("#grb");
startGRBTimer(60, display);
<div id="grb"></div>