我在这个网站上找到了这个倒数计时器(下面的代码),看来对我来说非常有用,直到达到零,然后开始为负数。
此代码的主要优点是刷新页面后不会重新启动。达到零时是否可以停止此代码?另外,是否可以对它进行编码,使其在页面刷新后重新启动,但仅在达到零后才重新启动,而不是在此之前重新启动?
此外,我希望最长的时间为25分钟,但我也很难做到这一点。
我尝试搜索解决方案,但是找不到刷新后未重新启动计数器的任何解决方案。任何帮助,将不胜感激。
<script type="text/javascript">
// properties
var count = 0;
var counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}
return val;
}
function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}
function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + " : " + minutes + " : " + seconds + ""; // watch for spelling
}
</script>
<div id="timer"></div>
<p>Timer should stop at zero and only restart on refresh after reaching zero</p>
</script>