patternjavascriptMinor
New year countdown
Viewed 0 times
countdownyearnew
Problem
Here's some code I wrote quickly to get a nice millisecond countdown going. It displays the number of milliseconds until the new year in whatever timezone is next to be in 2015 are in in huge font, and spits out the timezone in small reasonable font below.
Newyear Countdown
h1 {
font: 25vw "Helvetica Neue";
margin: 0;
}
Loading
Loading
var countdown = document.getElementById('countdown'),
timezoneText = document.getElementById('timezone'),
timezone = -12;
setInterval(function() {
countdown.removeChild(countdown.firstChild);
var text = new Date('2015-01-01T00:00:00Z').getTime() + 3600000 * timezone - new Date().getTime();
while (text 0 ? '+' : '') + (timezone || '')));
}, 0);
Solution
I think you've gotten the time zone handling wrong:
Here is an implementation of the timer for the local time zone (since that is what you originally specified in the question).
- The timer is useless for residents of time zones with non-integer offsets, such as India, Nepal, Iran, and Newfoundland.
- You've reversed the sense of the UTC offset. Time zones east of the Prime Meridian should generally have a positive offset; those to the west would have a negative offset.
- What happens in a day or two? It seems like it will keep trying to find a time zone with a ridiculous offset that has not yet reached 2015.
Here is an implementation of the timer for the local time zone (since that is what you originally specified in the question).
Newyear Countdown
h1 {
font: 25vw "Helvetica Neue";
margin: 0;
}
Loading
Loading
function formatTimezone(offsetMinutes) {
if (offsetMinutes == 0) return 'UTC';
var hours = Math.floor(Math.abs(offsetMinutes / 60));
var minutes = Math.round(Math.abs(offsetMinutes) % 60);
var sign = (offsetMinutes > 0) ? '+' : '-';
return 'UTC' + sign +
('00' + hours).slice(-2) +
('00' + minutes).slice(-2);
}
function millisecondsUntil(target) {
return target - Date.now();
}
var countdown = document.getElementById('countdown'),
target = (new Date(2015, 0, 1)).getTime(),
timezoneText = document.getElementById('timezone'),
timezoneOffsetMinutes = -(new Date()).getTimezoneOffset();
timezoneText.removeChild(timezoneText.firstChild);
timezoneText.appendChild(document.createTextNode('Milliseconds until new year 2015 in timezone ' + formatTimezone(timezoneOffsetMinutes)));
setInterval(function() {
var text = millisecondsUntil(target);
countdown.removeChild(countdown.firstChild);
countdown.appendChild(document.createTextNode(text));
}, 1);
Context
StackExchange Code Review Q#75404, answer score: 2
Revisions (0)
No revisions yet.