CSS Animation (with steps) vs JavaScript setInterval - CSS3 clock (stopwatch?)
Forked from http://jsfiddle.net/simurai/sXBxN/
by John Schulz
HTML
<div>
<time id="css">
<span class="hour"></span>
<span class="min"></span>
<span class="sec"></span>
</time>
<p>CSS (animation + <a href="http://dev.w3.org/csswg/css3-animations/#animation-timing-function">steps</a>)</p>
</div>
<div>
<time id="js">
<span class="hour"></span>
<span class="min"></span>
<span class="sec"></span>
</time>
<p>JS (setInterval)</p>
</div>
<p id="log"></p>
CSS
/* clock animation */
/* WebKit */
#css .hour { -webkit-animation: tick 4320s steps(12, end) infinite; }
#css .min { -webkit-animation: tick 360s steps(60, end) infinite; }
#css .sec { -webkit-animation: tick 6s steps(60, end) infinite; }
@-webkit-keyframes tick {
from { -webkit-transform: rotate( 0deg); }
to { -webkit-transform: rotate(360deg); }
}
/* Moz */
#css .hour { -moz-animation: tick 4320s steps(12, end) infinite; }
#css .min { -moz-animation: tick 360s steps(60, end) infinite; }
#css .sec { -moz-animation: tick 6s steps(60, end) infinite; }
@-moz-keyframes tick {
from { -moz-transform: rotate( 0deg); }
to { -moz-transform: rotate(360deg); }
}
/* just some basic styling */
time {
position: relative;
display: inline-block;
width: 200px; height: 200px;
border-radius: 100px;
background-color: #eee;
}
span {
position: absolute;
left: 100px;
height: 100px;
-webkit-transform-origin: bottom center;
-moz-transform-origin: bottom center;
}
.hour { box-shadow: black 0 0 0 5px; height: 50px; top: 50px; }
.min { box-shadow: black 0 0 0 3px; height: 80px; top: 20px; }
.sec { box-shadow: red 0 0 0 1px; height: 90px; top: 10px; }
div { display: inline-block; }
p { clear: both; }
/* I know. I'm sorry */
#css + p { margin-left: 25px; }
#js + p { margin-left: 50px; }
#log { margin-left: 75px; }
JavaScript
var hands, angle, log, frequency;
var moveHand = (function(){
var el = document.createElement('div');
return function(hand, angle){
hand.style['webkitTransform'] = 'rotate(' + angle + 'deg)';
}
})();
init();
animate();
function init()
{
var clock = document.getElementById('js');
hands = {
sec: clock.getElementsByClassName('sec')[0],
min: clock.getElementsByClassName('min')[0],
hour: clock.getElementsByClassName('hour')[0]
};
angle = {
current: {
sec: 0,
min: 0,
hour: 0
},
increment: {
sec: 360/60,
min: 360/60,
hour: 360/12
}
};
frequency = 100;
}
function animate()
{
if (!animate.started) animate.started = +new Date;
setInterval(function(){
draw();
}, frequency);
}
function draw()
{
angle.current.sec += angle.increment.sec;
moveHand(hands.sec, angle.current.sec);
if (angle.current.sec === 360) {
angle.current.sec = 0;
angle.current.min += angle.increment.min;
moveHand(hands.min, angle.current.min);
if (angle.current.min === 360){
angle.current.min = 0;
angle.current.hour += angle.increment.hour;
moveHand(hands.hour, angle.current.hour);
if (angle.current.hour === 360){
angle.current.hour = 0;
}
}
}
}