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

标签 javascript

我正在开发一系列 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/

相关文章:

javascript - 克 :submitButton conditional enable/disable

javascript - 逗号后将数字舍入为 2 位数字

javascript - 在多个页面的js变量html中存储链接名称

javascript - Ember 的 titleBinding on a link-to helper 破坏了 Jasmine 测试

javascript - 使用 Algolia 和 Typeahead 在网站中提及用户

javascript - IF ELSE 语句在第一个 IF 上始终返回 True

javascript - 将对象引用保存到数组的性能问题

javascript - FlotChart - 如何为折线图中的特定系列分配颜色?

javascript - 如果选中则显示提交按钮

javascript - 难以理解所选插件的 JavaScript 语法,需要建议