IPE_timer - A Real time Timer //usage: var tt = IPE_timer.getT(); tt.start(function(CurrentTime){ console.log('current Time in seconds ' + CurrentTime); });
var IPE_Timer = (function(){
// Self calling function
// Private property for holding the only existing instance
var T;
var createTimer = function(){
// Private properties
var stop_flag = false;
var speed = 1000;
var count = 0;
var start_time = new Date().getTime();
var onTick = function(){};
// Private methods
var tick = function(){
count = count + speed;
if ( stop_flag ) {
return;
}
onTick( ( count / 1000 ) );
set_ticker();
};
var set_ticker = function(){
var diff = (new Date().getTime() - start_time) - count;
setTimeout( function(){
tick();
}, (speed - diff));
};
var stop = function(){
stop_flag = true;
};
var pause = function(){
stop();
};
var resume = function(){
stop_flag = false;
set_ticker();
};
var start = function(callback){
count = 0;
onTick = callback;
start_time = new Date().getTime();
set_ticker();
};
return {
// returns methods which is a
// closure with access to private properties.
tick: tick,
stop: stop,
pause: pause,
resume: resume,
start: start
};
};
return {
// Method for creating instance of Timer.
getT: function(){
// Condition checking existence of instance
if(!T){
T = createTimer();
}
// If instance already existing returning the same.
return T;
}
};
})();
/*
//usage:
var tt = IPE_timer.getT();
tt.start( function( CurrentTime ){
console.log('current Time in seconds ' + CurrentTime);
});
*/