简体   繁体   English

JavaScript每周五重复倒计时至中午

[英]Javascript repeating countdown to Midday every Friday

Im after some code which will display days, hours and minutes which counts down the days, hours and minutes left til midday every Friday? 我在一些显示天,小时和分钟的代码之后,该代码将每个星期五剩下的天,小时和分钟数倒计时吗?

(When midday friday is reached I would like the counter to start again to countdown to the next Friday midday, so the timer repeats over and over?) (到达中午星期五时,我希望计数器再次开始倒数到下一个星期五中午,所以计时器重复一遍又一遍?)

Not sure how to go about doing this as I am relatively new to JS 由于我是JS的新手,所以不确定如何去做

Any help much appreciated! 任何帮助,不胜感激!

There are lots of questions here on timers and countdowns, you should be able to work out something basic from them. 这里有很多关于计时器和倒数的问题,您应该能够从中得出一些基本的信息。 A very simple countdown to noon next Friday is: 下周五中午的倒计时非常简单:

 function update(){ // Get current date and time var today = new Date(); // Get number of days to Friday var dayNum = today.getDay(); var daysToFri = 5 - (dayNum < 5? dayNum : dayNum - 7); // Get milliseconds to noon friday var fridayNoon = new Date(+today); fridayNoon.setDate(fridayNoon.getDate() + daysToFri); fridayNoon.setHours(12,0,0,0); // Round up ms remaining so seconds remaining matches clock var ms = Math.ceil((fridayNoon - today)/1000)*1000; var d = ms / 8.64e7 | 0; var h = (ms % 8.64e7) / 3.6e6 | 0; var m = (ms % 3.6e6) / 6e4 | 0; var s = (ms % 6e4) / 1e3 | 0; // Return remaining return d + 'd ' + h + 'h ' + m + 'm ' + s + 's'; } // Run update just after next full second function runUpdate() { var el = document.getElementById('toFriday'); el.innerHTML = update(); setTimeout(runUpdate, 1020 - (Date.now()%1000)); } runUpdate(); 
 <div>Remaining to noon next Friday: <span id="toFriday"></span> 

This is a very basic implementation and will skip when it goes over a daylight saving boundary (which can be avoided), but it should suit for a simple countdown where the hours remaining is not critical. 这是一个非常基本的实现,当它越过夏时制边界时可以跳过(可以避免),但是它应该适合于剩余时间不是很关键的简单倒计时。 It will only be wrong for a short time: 这只会在短时间内是错误的:

  • in places where daylight saving is observed, 在观察到夏令时的地方,
  • on the two days of the year where daylight saving changes have an effect, and 在一年中的两天,夏令时更改会生效,并且
  • if the change is not at midnight 如果更改不是在午夜

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

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