EDIT 1: New version with namespace & single raF
- Custom Namespace
- one Single raF controls all timers
- the timer index is reset to 0
- every resource-intensive function or nested variable is cached
- all functions are just references
- theoretically the max delay is 17ms
- uses bitwise & short hand operators to increase performance
I tested 10000 timers in 5sec and it worked without slowdown.
The loop run at stable 17ms==60fps==60HZ.
And The maximum delay was around 10ms.
;(function(ns){
var index=0, // increases or uid until there are no more timers then set to 0
timers=[], // contains all timers
L=0, // static timers.length (increases performance)
now=Date.now, // shortcut
raf=window.requestAnimationFrame, // shortcut
test=0; // variable to calculate the average update time in ms
function globalTimer(){ // the global timing function
var l=L,n=now(),t;
l>0?raf(globalTimer):
(
index=0,
test=0,
console.log(
'Stopping Global Timer and Setting Global Index To '+
index+', also test to '+test
)
);
while(l--){
t=timers[l];//t=[index,callback,delay,offset,startTime]
n-t[3]<t[2]||
(
//t[3]+=t[2], // this is for the setInterval function
t[1](),
timers.splice(l,1),
L=timers.length,
console.log([
'Delay Set: ',t[2],
' - Time Passed: ',n-t[4],
' - Update every: ',(n-t[4])/test,'ms'
].join(''))
);
}
test++
}
ns.setTimeout=function(cb,delay){
var i=index++,n=now();
L||(raf(globalTimer),console.log('Executing Global Timer'));
L=timers.push([i,cb,delay,n,n]);
return i
}
ns.clearTimeout=function(i){
var l=L;
while(l--){
timers[l][0]!=i||(timers.splice(l,1))
}
}
/*ns.setInterval=function(callback,delay){...}
ns.clearInterval=function(callback,delay){...}*/
}(this.Timers=this.Timers||{}));
Usage
var T1=Timers.setTimeout(function(){console.log('new timer')},3000);
Timers.clearTimeout(T1);
So basically i tried to put less possible calculations inside the globaltimer function.
even if i could put the cleartimeout index check inside the globaltimer i created a distinct while loop.but i'm not shure if it's better or not.(atm i'm thinking of some sort of indexof...)
Demo
http://jsfiddle.net/G34Sr/