【问题标题】:need help fixing a countdown clock with javascript需要帮助使用 javascript 修复倒计时时钟
【发布时间】:2020-05-08 19:24:44
【问题描述】:

我正在尝试创建一个倒计时时钟并且遇到了一些障碍。它正在显示最终数字,即我不想要的 for 循环的最终结果。我的目标是每次循环时都必须循环触发我的 .setTimeout 。我将不胜感激。

const countdownClock = (ranNum) => {
    const startingNum = ranNum * 50;
    for(let i = startingNum; i > 0; i--) {
        setTimeout(() => countdownSpan.textContent = [i], 1000);
    }
}

【问题讨论】:

  • 什么意思?

标签: javascript html loops for-loop countdown


【解决方案1】:

这是因为 setTimeout 正在等待 1s 执行,直到那时循环在您的第一个 setTimeout 触发之前完成,并且当您的第一个超时被触发时,i 的值被更新并且是现在是循环的最后一个数字。您可以使用promisesasync/await 处理它。

const countdownClock = async (ranNum) => {
    const startingNum = ranNum * 50;
    for(let i = startingNum; i > 0; i--) {
        await new Promise(resolve => {
         setTimeout(() => {
            countdownSpan.textContent = [i];
            resolve()
         }, 1000)
       });
    }
}

希望对你有帮助!

【讨论】:

  • 非常感谢,非常感谢。
【解决方案2】:

在当前函数完成之前,定时器函数不会触发。这就是为什么您的 for 循环在计时器函数运行之前运行完成的原因。为了看到计时器滴答作响,您根本不应该使用循环,因为计时器将创建循环功能。您只需要递归的 setInterval()setTimeout()

const element = document.getElementById("countdown");

let startingNum = parseInt(Math.random() * 50, 10);
let timer = null;

function counter(){
  // Clear any running timer to prevent multiple
  // timers from stacking up in the event queue
  clearTimeout(timer); 
  
  startingNum--; // Decrease the counter
  
  // If the count is greater than 0
  if(startingNum >-1){
    element.textContent = startingNum;

    // Set a new timer up to call this function
    timer = setTimeout(counter, 1000); 
  }   
}

// Start the process off
timer = setTimeout(counter, 1000);
<div id="countdown"></div>

【讨论】:

  • 嗨 Scott,函数 counter 可能没有退出条件并且它永远不会停止递归循环吗?
  • @Pierfrancesco 我已经更新了我的答案并将递归计时器调用移到了if 条件中,以保证设置一个新的计时器。如果你没有落入那个分支,你就不会设置一个新的定时器,定时器就会停止。
  • @AndrewLovato 不客气。不要忘记通过单击答案左上角的复选标记将其标记为“答案”。
猜你喜欢
  • 2018-11-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 2014-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多