gpt4 book ai didi

javascript - 显示多个 JavaScript 倒计时

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:13 24 4
gpt4 key购买 nike

我找到了一种使用 javascript 显示多个倒计时的方法。 Having multiple countdown timer events intervals in javascript

我正在尝试在网格中创建一个“更温暖”的显示。我选择了 HTML 表格。我有草稿here

我无法在表格单元格中显示倒计时,并且时间部分是分开的。我在“天数”列中只有整个 SPAN 标记。

最佳答案

我会采取不同的方法。首先,我不会在 HTML 中创建表格,而是将有关倒数计时器的数据存储在 JavaScript 代码中的对象数组中,然后使用 JS 生成表格。这样做会使它更干净,更易于维护;要添加新元素,您只需将一个对象添加到数组中,而不必使用 HTML。

其次,我不会为每个计时器启动一个间隔,而是创建一个更新所有计时器的间隔。使用单个时间间隔意味着您的 DOM 更新将被一起批处理并且将 minimize page reflow .

此代码还会在每次更新时重新计算剩余时间。如果你计算一次然后每一轮都减去,它可能会在你的计数器中引入漂移。这是因为 setInterval 只保证它会等待 至少 您在 delay 参数中指定的毫秒数,it could be more .除非您的计时器连续运行很长时间,否则这可能无关紧要,但随着时间的推移它会变得不准确。

// data is an array of objects, each representing one of your categories.
// Each category has a .title to store its title and a .counters that
// stores an object for each counter in that category.
var data = [
{
title: 'ASTRONOMY',
counters: [
// Each counter has a .title and a .date that is parsed by new Date()
{
title: 'Total Solar Eclipse - (NE US)',
date: 'August 21, 2017'
},
{
title: 'Next Supermoon - Full',
date: 'December 3, 2017'
}
]
},
{
title: 'POLITICS',
counters: [
{
title: 'Next Presidential Election',
date: 'November 3, 2020'
}
]
},
{
title: 'TEST',
counters: [
{
title: '30 seconds from page load',
date: (new Date()).getTime() + (30 * 1000)
},
{
title: 'Unix Epoch',
date: 'January 1, 1970'
}
]
}
];
// this reduce generates the table
let table = data.reduce((acc, category, categoryIndex) => {
return acc + `<tr><td colspan="6" class="category">${category.title}</td></tr>` +
category.counters.reduce((acc, counter, index) => {
return acc + `<tr id="counter-${categoryIndex}-${index}">
<td>${counter.title}</td>
<td>${counter.date}</td>
<td class="days"></td>
<td class="hours"></td>
<td class="minutes"></td>
<td class="seconds"></td>
</tr>`;
}, '');
}, '<table class="countdown"><tr><th>Event</th><th>Date</th><th>Days</th><th>Hours</th><th>Minutes</th><th>Seconds</th></tr>');
table += '</table>';

// insert the table after the noscript tag
document.getElementById('countdown').insertAdjacentHTML('afterend', table);

// generate a flat list of counters
let counters = data.reduce((acc, category, categoryIndex) => {
return acc.concat(category.counters.reduce((counterAcc, counter, index) => {
return counterAcc.concat([{
// counters will be an array of the objects we generate here.
// node contains a reference to the tr element for this counter
node: document.getElementById(`counter-${categoryIndex}-${index}`),
// date is the date for this counter parsed by Date and then converted
// into a timestamp
date: (new Date(counter.date)).getTime()
}]);
}, []));
}, []);

const msSecond = 1000,
msMinute = msSecond * 60,
msHour = msMinute * 60,
msDay = msHour * 24;
let intervalId;

function updateCounters () {
counters.forEach((counter, counterIndex) => {
let remaining = counter.date - Date.now(),
node = counter.node;
let setText = (selector, text) => node.querySelector(selector).textContent = text;

if (remaining > 0) {
setText('.days', Math.floor(remaining / msDay));
remaining %= msDay;
setText('.hours', Math.floor(remaining / msHour));
remaining %= msHour;
setText('.minutes', Math.floor(remaining / msMinute));
remaining %= msMinute;
setText('.seconds', Math.floor(remaining / msSecond));
} else {
// make sure we don't accidentally display negative numbers if a timer
// firing late returns a past timestamp (or the data contains a past date)
setText('.days', 0);
setText('.hours', 0);
setText('.minutes', 0);
setText('.seconds', 0);

// This countdown has reached 0 seconds, stop updating it.
counters.splice(counterIndex, 1);
// no more counters? Stop the timer
if (counters.length === 0) {
clearInterval(intervalId);
}
}
});
}
// display counters right away without waiting a second
updateCounters();
intervalId = setInterval(updateCounters, 1000);
 table {
border-collapse: collapse;
}
tr:nth-child(even) {
background-color: #edf;
}
.category {
font-weight: bold;
}
td, th {
padding: .5em;
}
.days, .hours, .minutes, .seconds {
text-align: right;
}
 <noscript id="countdown">Sorry, you need JavaScript enabled to view the count
downs</noscript>

更多阅读

关于javascript - 显示多个 JavaScript 倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158339/

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