gpt4 book ai didi

javascript倒计时回显错误的时间

转载 作者:行者123 更新时间:2023-11-30 15:24:56 27 4
gpt4 key购买 nike

我希望我的 javascript 代码能够读取 3 小时倒计时,并在倒计时完成后重定向到新页面

<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>

请帮助我让它能够倒计时到三个小时,并在倒计时完成后重定向到另一个页面,让它变得更好

最佳答案

您没有正确设置总时间。您将其设置为 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()

关于javascript倒计时回显错误的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43147344/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com