javascript implementation of an event based clock for any animation

nov 14 2019, 1:52pm

I'm not sure if this little clock would be useful. And I haven't made it fully compatible to all browsers too. It is included here as tests showed that there was almost no performance degradation.

clock.js

'use strict';

function Clock(el, fps){

	//private
	
	var id = null,
		t0 = performance.now(),
		tD = 1000 / fps;//delay [ms] between a frame to the next

	function ticks(t){
		id = requestAnimationFrame(ticks);
		if(t - t0 > tD){
			t0 = t;//now becomes past
			var ev = new Event('ticks');
			el.dispatchEvent(ev);//ticks the element
		}
	}
		
	//public
	
	this.start = function(){
		if(!id)
			ticks();
	};

	this.stop = function(){
		if(id){
			cancelAnimationFrame(id);
			id = null;
		}
	};
}
			

Usage / implementation

<div id="game">
	<canvas width="1000" height="1000">HTML5 canvas isn't supported by your browser, please upgrade it.</canvas>
	<label>run<input id="game-run" type="checkbox"></label>
	<label>score<input id="game-score" type="text" readonly></label>
</div>
<script src="clock.js"></script>
<script>
	'use strict';
	+function(){
		//variables
		var game = document.getElementById('game'),
			canv = game.getElementsByTagName('canvas')[0],
			ctx = canv.getContext('2d'),
			clock = new Clock(canv, 10),//el is canvas, fps = 10
			runCB = game.querySelector('#game-run');

		//setup event handlers

		canv.addEventListener('ticks', function(ev){
			//draw something here after clearing canvas
			ctx.clearRect(0, 0, canv.width, canv.height);
		}, false);

		runCB.addEventListener('change', function(){
			if(this.checked)
				clock.start();
			else
				clock.stop();
		}, false);

		//on page load, synchrohize clock with checkbutton value
		if(runCB.checked)
			clock.start();
	}();
</script>
			

www.000webhost.com