Web Browser (Client Side) Timers

6:15 AM 2/19/2019

ball

Pick a timer:

There are 3 types of timers inside any modern browsers: the famous setTimeout() which works in any types and versions of browsers, the energy-efficient requestAnimationFrame() and lastly... the hidden gem CSS animation.

As you can see in test above, each is capable to move the ball quite smoothly. Ball movement itself is defined by a stepping javascript function moveBall() as follows:

const ball = test.getElementsByTagName('span')[0];
let v = { //2D speed
	x: 0.1, 
	y: 0.1
};

function moveBall(){
	let s = { //2D coordinate
		x: Number(ball.style.left.split('em')[0]),
		y: Number(ball.style.top.split('em')[0])
	}
	if((s.x < 0 && v.x < 0) || (s.x > 13 && v.x > 0))
		v.x = -v.x;
	if((s.y < 0 && v.y < 0) || (s.y > 4 && v.y > 0))
		v.y = -v.y;
	ball.style.left = (s.x + v.x) + 'em';
	ball.style.top = (s.y + v.y) + 'em';
}
		

And here's how each timers calls the step function:

setTimeout()

function funcST(){
	setTimeout(funcST, 100);
	moveBall();
}
		

requestAnimationFrame()

let tRAF = performance.now();
function funcRAF(t){
	requestAnimationFrame(funcRAF);
	if(t - tRAF > 100){
		moveBall();
		tRAF = t;
	}
}
		

CSS Animation

<style>
	#test fieldset input[value="3"]:checked{
		animation: 100ms infinite vibrate;
	}
	@keyframes vibrate{
		from{margin-right: 0px;} /* turns out that this line and the next, */
		to{margin-right: 2px;}   /* don't have to have different values ! */
	}
</style>
		

Whenever you choose "CSS Animation" as the timer, choice text will vibrate and this generates javascript "animationiteration" event. This event bubbles and thus is detected by element's parent to invoke the moveBall() repetitively (see following javascript).

<script>
	test.addEventListener('animationiteration', function(){
		moveBall();
	}, false);
</script>
		

Cool, right?

Comments