Reputation: 13
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
Any help much appreciated!
Upvotes: 0
Views: 1530
Reputation: 147363
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:
Upvotes: 1