简体   繁体   English

显示多个JavaScript倒数

[英]Display of Multiple JavaScript Countdowns

I found a way to display multiple countdowns, using javascript. 我找到了一种使用javascript显示多个倒计时的方法。 Having multiple countdown timer events intervals in javascript 在JavaScript中具有多个倒数计时器事件间隔

I am trying to create a "warmer" display, in a grid. 我试图在网格中创建一个“较暖”的显示。 I opted for an HTML table. 我选择了HTML表。 I have a draft here 在这里有草稿

I can't get the countdowns to display in the table cells, with separated time components. 我无法将倒计时显示在具有单独时间成分的表格单元格中。 I just have the entire SPAN tag in the "Days" column. 我在“天数”列中只有整个SPAN标签。

I'd take a different approach. 我会采取另一种方法。 First of all, instead of creating the table in your HTML, I would store the data about the countdown timers in an array of objects in your JavaScript code and generate the table using JS. 首先,不是在HTML中创建表格,而是将有关倒数计时器的数据存储在JavaScript代码中的对象数组中,然后使用JS生成表格。 Doing this will make it cleaner and more maintainable; 这样做将使其更清洁,更易于维护。 to add new items you can just add an object to the array instead of mucking about with HTML. 要添加新项目,您只需将一个对象添加到数组中,而不用HTML来处理。

Secondly, instead of starting an interval for each timer, I would create a single interval that updates all of the timers. 其次,我不会为每个计时器启动一个间隔,而是创建一个可以更新所有计时器的间隔。 Using a single interval means your DOM updates will be batched together and will minimize page reflow . 使用单个间隔意味着您的DOM更新将被分批处理,并将最大程度地减少页面重排

This code also recalculates the time left each time it updates. 该代码还会重新计算每次更新后剩余的时间。 If you calculate it once and then just subtract each round, it could introduce drift into your counter. 如果您只计算一次,然后每轮减去一次,则可能会将漂移引入计数器。 This is because setInterval only guarantees that it will wait at least as many milliseconds as you specify in the delay parameter, it could be more . 这是因为setInterval仅保证它将等待至少与在delay参数中指定的毫秒一样多的毫秒, 它可能更长 It probably wouldn't matter much unless your timer was running continuously for a very long time, but over time it would be come inaccurate. 除非您的计时器长时间连续运行,否则可能无关紧要,但是随着时间的流逝,它会变得不准确。

 // 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> 

More Reading 更多阅读

If you are ok to use any javascript library why not check FlipClock.js out. 如果可以使用任何JavaScript库,为什么不检查FlipClock.js

As per the text provided on their site, the following are the logical requirements that were considered when creating the API. 根据其站点上提供的文本,以下是创建API时考虑的逻辑要求。

  • Use as a clock 用作时钟
  • Use as a timer 用作计时器
  • Use as a countdown 用作倒计时
  • Themeable using pure CSS 使用纯CSS主题化
  • Clean & Dry Syntax 清洁和干燥语法
  • Abstract everything into reusable objects 将所有内容抽象为可重用的对象
  • Full-Featured Developer API to create custom “Clock Faces” 功能齐全的Developer API,可创建自定义“时钟面孔”

And if you are not ok to use any library here is what you can learn from about how to create a countdown timer using javascript 如果您不能使用任何库,那么您可以从中学习如何使用JavaScript创建倒数计时器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM