gpt4 book ai didi

javascript - 为什么我的计时器条会停在某个点?

转载 作者:行者123 更新时间:2023-11-30 14:11:36 25 4
gpt4 key购买 nike

我正在开发一系列 Javascript、CSS 和 HTML 迷你游戏。在这些游戏中,我在进度/计时器栏上使用了一个计时器。在这里,条形图移动到某个点。问题是在所有游戏中它都能完美运行,除了一个游戏并且代码在所有游戏中都是相同的。

这是进度/计时器栏的代码:

const leftTime = document.getElementById("leftTime");
const countDown = document.getElementById("countDown");
function initBarCount() {
let startTimer = setInterval(barCount, 480); //width of bar is 250px
console.log("start timer: " + startTimer);
function barCount() {
if (leftTime.clientWidth < countDown.clientWidth) {
leftTime.style.width = leftTime.clientWidth + 1 + "px";
console.log("1: " + leftTime.style.width);
} else {
leftTime.style.width = countDown.clientWidth + "px";
console.log("2: " + leftTime.style.width);
clearInterval(startTimer);
}
}
}

这是定时器的代码。 (2 分钟)

function startTimerGame() {
setTimeout(function() {
if (container.style.display == "none") { //open/close container
container.style.display = "block";
} else {
container.style.display = "none";
}
guessField.value = ""; //reset input
createGame(); //start game variables
resultText.innerHTML = "El resultado final es: " + finalScore;
playGameButton.disabled = false;
}, 120000 /*300000*/);
}

这是您点击开始游戏的按钮的代码。

playGameButton.onclick = function() {
resultText.innerHTML = "";
finalScore = 0;
leftTime.style.width = 0 + "px";
startTimerGame();
initBarCount();
if (container.style.display == "none" || playGameButton.disabled == false) {
container.style.display = "block";
playGameButton.disabled = true;
} else {
container.style.display = "none";
playGameButton.disabled = false;
}
};

我注意到有问题的游戏发生了一些奇怪的事情:对正在发生的事情有什么建议吗?如果您能告诉我问题出在哪里,我将不胜感激,因为我不知道如何继续,老实说,这种语言对我来说是新的。

最佳答案

也许 clientWidth 属性的更新时间比调用下一个时间间隔要长。尝试将间隔设置得更长一些,看看是否可以解决问题。

如果您仍想使用相同的短间隔,请尝试执行以下操作:

leftTime.style.width = (parseInt(leftTime.style.width,10) + 1) + 'px';

关于javascript - 为什么我的计时器条会停在某个点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54333609/

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