2017-03-31 31 views
1

我想这是我的JavaScript代码能够被读取3小时倒计时,并重定向到倒计时后,一个新的页面完成JavaScript的倒计时附和错误的时间

<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 + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling 
} 
</script> 
<div id="timer"></div> 

请帮助我变得更好用使其倒计时到三小时,倒计时完成后又重定向到另一页

回答

2

您没有正确设置总时间。您将其设置为16分钟而不是3小时。这里是工作的代码(试试JSFiddle):

var time = 60 * 60 * 3; 
var div = document.getElementById("timer"); 
var t = Date.now(); 

var loop = function(){ 
    var dt = (Date.now() - t) * 1e-3; 

    if(dt > time){ 
    doWhateverHere(); 
    }else{ 
    dt = time - dt; 
    div.innerHTML = `Hours: ${dt/3600 | 0}, Minutes: ${dt/60 % 60 | 0}, Seconds: ${dt % 60 | 0}`; 
    } 

    requestAnimationFrame(loop); 
}; 

loop(); 

另外,不要使用setIntervalsetTimeout精确计时。这些功能是不稳定的。改为使用Date.now()

+0

我只是想让你帮我检查一下我将在三个小时内完成任务而不改变我的代码。 – phemieny7

+0

@ phemieny7。 'count = getLocalStorage('count')|| 3600 * 3'而不是'count = getLocalStorage('count')|| 1000'。但我**强烈**推荐你不要在这种情况下使用'setInterval'和'setTimeout'函数。 – user7771338

+0

是的,我爱你的代码,但我得到的问题是,它重新启动时,页面刷新。如果你能纠正这一点,我真的很喜欢使用它。请帮我纠正一下。谢谢。 – phemieny7