【问题标题】:Multiple consecutive 5 minute countdown timers多个连续 5 分钟倒计时
【发布时间】:2021-03-10 15:36:34
【问题描述】:

我想制作 3 个倒数计时器,下一个计时器在最后一个计时器结束时开始(第一个计时器会自动开始倒计时,但第二个计时器只会在第一个计时器到达 0:00 和第三个计时器时开始一个只会在第二个到达 0:00 时开始)。

我找到了倒数计时器的代码:

    function countDown() {
        var seconds = 60; 
        var mins = 5;
        function clickClock() {
            var counter = document.getElementById("countdown1");
            var currentMinutes = mins - 1; 
            seconds--; 
            counter.innerHTML = currentMinutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
            if(seconds > 0) {
                setTimeout(clickClock, 1000);
            } else {
                if(mins > 1) {
                    countDown(mins-1);
                }
            }
        }
        clickClock();
    }
    countDown();

在我的 HTML 中,我有 3 个跨度,每个跨度都有一个唯一 ID(#countdown1、#countdown2、#countdown3)

我尝试将一个参数传递给 clickClock() 函数,称为 counter,这样每当我调用该函数时,我就可以输入我想要影响的元素的 id,但没有用。

我可以只做 2 个其他函数,它们会做完全相同的事情,但会改变计数器变量,但我想避免在我的代码中重复不必要的事情。

这是怎么做到的?

任何帮助表示赞赏:)

【问题讨论】:

    标签: javascript timer countdown


    【解决方案1】:

    我会这样做:

    /////////// USAGE
    const timersDurationInMilliseconds = 1000 * 5; // for 5 minutes do: 1000 * 60 * 5
    
    // Render initial timer content
    RenderTimer('countdown1', timersDurationInMilliseconds);
    RenderTimer('countdown2', timersDurationInMilliseconds);
    RenderTimer('countdown3', timersDurationInMilliseconds);
    
    // Start countdown, then start another ones
    countDown(timersDurationInMilliseconds, 'countdown1')
      .then(() => countDown(timersDurationInMilliseconds, 'countdown2'))
      .then(() => countDown(timersDurationInMilliseconds, 'countdown3'))
      .then(() => alert('All timers finished!'));
    
    
    /////////// REQUIRED METHODS
    function countDown(durationInMilliseconds, elementId) {
      return new Promise((resolve, reject) => {
        const updateFrequencyInMilliseconds = 10;
        const currentTimeInMilliseconds = new Date().getTime();
        const endTime = new Date(currentTimeInMilliseconds + durationInMilliseconds);
        
        function updateTimer(elementId) {
          let timeLeft = endTime - new Date();
          if (timeLeft > 0) {
            // We're not done yet!
            setTimeout(updateTimer, updateFrequencyInMilliseconds, elementId);
          } else {
            // Timer has finished!
            resolve();
            
            // depending on update frequency, timer may lag behind and stop few milliseconds too late
            // this will cause timeLeft to be less than 0
            // let's reset it back to 0, so it renders nicely on the page
            timeLeft = 0;
          }
          
          RenderTimer(elementId, timeLeft);
        }
    
        updateTimer(elementId);
      });
    }
    
    function padNumber(number, length) {
      return new String(number).padStart(length || 2, '0'); // adds leading zero when needed
    }
    
    function RenderTimer(elementId, timeLeft) {
      const hoursLeft = Math.floor(timeLeft / 1000 / 60 / 60 % 60);
      const minutesLeft = Math.floor(timeLeft / 1000 / 60 % 60);
      const secondsLeft = Math.floor(timeLeft / 1000 % 60);
      const millisecondsLeft = timeLeft % 1000;
    
      const counterElement = document.getElementById(elementId);
      counterElement.innerHTML = `${padNumber(hoursLeft)}:${padNumber(minutesLeft)}:${padNumber(secondsLeft)}.${padNumber(millisecondsLeft, 3)}`;
    }
    <p>First countdown: <span id="countdown1"></span></p>
    <p>Second countdown: <span id="countdown2"></span></p>
    <p>Third countdown: <span id="countdown3"></span></p>

    如果您只想显示分钟和秒,您可以在RenderTimer 方法中调整该行为。

    如果您不打算向用户显示毫秒,您可能希望通过调整 updateFrequencyInMilliseconds 变量(例如从 10 毫秒到 1000 毫秒)来更改计时器在页面上更新和呈现的频率。

    【讨论】:

    • 非常感谢! Dziękuję Ci!
    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多