如何在 Javascript 中同时渲染和更新多个定时器?

How to render and update multiple timers at the same time in Javascript?

我正在尝试构建一个函数来显示从 Firestore 上存储的数据呈现的多个计数器。

当我只是 运行 计数器的静态计算时,它们 return 正确的字符串,但是当我每秒尝试 运行 该函数时,我得到不同的输出:

显示屏显示连续的数字计数(例如 16、17、18)而不是 3 次倒计时(格式为“T-天、小时、分钟、秒”)。

如果我在函数内部构建区间,那么我会得到未定义的。

我哪里做错了,我该如何解决?

倒计时功能

function countThis(date){
    const now = new Date().getTime();      
    const distance = date - now;
    const days = Math.abs(Math.floor(distance / (1000 * 60 * 60 * 24)));
    const hours = Math.abs(Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)));
    const minutes = Math.abs(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)));
    const seconds = Math.abs(Math.floor((distance % (1000 * 60)) / 1000));

    if (distance > 0) { 
        const calc = `T- ${days}D ${hours}H ${minutes}M ${seconds}S`;
        return calc;
    }
    else if (distance < 0) {                        
        const calc = `T+ ${days}D ${hours}H ${minutes}M ${seconds}S`;
        return calc;
    }
};

计数器渲染

const counters = (data) => {            
    let html = '';
    data.forEach(doc => {
        const data = doc.data();
        const date = data.timestamp.toDate();
        const counter = 
            `<div class="counter">
                <h5>` + dateFormat(date) + `</h5>
                <h4 class="activeCount">` + setInterval(countThis(date), 1000) + `</h4>
                <p class="micro">${data.title}</p>
            </div>`;
        html += counter;
    });
    counterModule.innerHTML += html;
}

几个问题:

  • setInterval returns 创建间隔的唯一标识符:这不是您想要在 HTML
  • 中输出的内容
  • setInterval 需要回调函数,但您 执行了 函数,并将其 return 值传递给 setInterval
  • 您为每次倒计时调用 setInterval,而您应该只有一个计时器来更新所有倒计时。
  • HTML 只被设置为 counterModule 一次,再也不会了。您需要在每个时间间隔更新 HTML。

这里是 counters 的更正:

const counters = (data) => {        
    let html = '';
    data.forEach(doc => {
        const data = doc.data();
        const date = data.timestamp.toDate();
        // Don't call setInterval here:
        const counter = 
            `<div class="counter">
                <h5>${dateFormat(date)}</h5>
                <h4 class="activeCount">${countThis(date)}</h4>
                <p class="micro">${data.title}</p>
            </div>`;
        html += counter;
    });
    counterModule.innerHTML = html; // NOT +=, but just =
}

假设定义了data,主要代码应该是这样的:

setInterval(() => counters(data), 1000);