|
// Assumes a non-negative number. |
|
function pad2(number) { |
|
if (number < 10) return '0' + number; |
|
else return '' + number; |
|
} |
|
function pad3(number) { |
|
if (number < 10) return '00' + number; |
|
else if (number < 100) return '0' + number; |
|
else return '' + number; |
|
} |
|
|
|
function draw(timestamp) { |
|
var now = new Date(); |
|
// No need for getElementById() because ids are already available on the window object. |
|
window.hours.textContent = pad2(now.getHours()); |
|
window.minutes.textContent = pad2(now.getMinutes()); |
|
window.seconds.textContent = pad2(now.getSeconds()); |
|
window.milliseconds.textContent = pad3(now.getMilliseconds()); |
|
|
|
window.requestAnimationFrame(draw); |
|
} |
|
|
|
window.requestAnimationFrame(draw); |
|
|
|
////////////////////////////////////////////////////////////////////// |
|
|
|
// Throttling the resize event, to prevent it from running too many times in sequence. |
|
// https://developer.mozilla.org/en-US/docs/Web/Events/resize |
|
(function() { |
|
var throttle = function(type, name, obj) { |
|
obj = obj || window; |
|
var running = false; |
|
var func = function(ev) { |
|
if (running) { return; } |
|
running = true; |
|
requestAnimationFrame(function() { |
|
obj.dispatchEvent(new CustomEvent(name, {detail: ev})); |
|
running = false; |
|
}); |
|
}; |
|
obj.addEventListener(type, func); |
|
}; |
|
|
|
throttle('resize', 'optimizedResize'); |
|
})(); |
|
|
|
function adjustSize(ev) { |
|
var style = window.getComputedStyle(window.clock); |
|
var fontSize = style.fontSize; |
|
|
|
if (!fontSize.endsWith('px')) console.warn('Expected fontSize ending in "px", found: ' + fontSize); |
|
fontSize = parseInt(fontSize, 10); |
|
|
|
if (window.clock.offsetWidth / window.clock.offsetHeight > window.innerWidth / window.innerHeight) { |
|
var newSize = fontSize * window.innerWidth / window.clock.offsetWidth; |
|
} else { |
|
var newSize = fontSize * window.innerHeight / window.clock.offsetHeight; |
|
} |
|
|
|
window.clock.style.fontSize = newSize + 'px'; |
|
// This should work on almost all cases (because the Math is correct), |
|
// but a nice improvement would be to check if the new dimensions are correct |
|
// and adjust the font-size as/if needed. |
|
} |
|
|
|
window.addEventListener('optimizedResize', adjustSize); |
|
adjustSize(null); |