Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript engine for loops. You can register and unregister functions and use just a single Interval to fire them all each iteration. Optimization is welcomed. I already tried to replace the interval with a RequestAnimationFrame but the result was not as fast as I expected - in fact slower!!
(function($) {
// GLOBALS
$.STSR_FOCUS_TARGET;
$.STSR_ENGINE;
$.STSR_ENGINE_SPEED;
$.STSR_ENGINE_PROCESSES = [];
$.STSR_ID = 0;
$.ENGINE = {// initialize values
init:function(ops){
$.STSR_ENGINE_SPEED = ops.speed;
},
status:'off',
/*/////////////////////////////////
StripTeser Engine Methods:
stop, start, register, unregister
/////////////////////////////////*/
// Iteration interval
run:function(){
var i = $.STSR_ENGINE_PROCESSES.length;
while(i--){
var fn = $.STSR_ENGINE_PROCESSES[i].process;
var v = $.STSR_ENGINE_PROCESSES[i].values;
fn(v);
}
},
// Stop iteration interval
stop:function(){
if(!$.STSR_ENGINE || $.STSR_ENGINE==undefined) return false;
clearInterval($.STSR_ENGINE);
$.STSR_ENGINE_PROCESSES = [];
$.STSR_ENGINE = null;
$.STSR_ID = 0;
this.status = 'off';
},
// Start iteration interval
start:function(){
if($.STSR_ENGINE==null)
{
$.STSR_ENGINE = setInterval($.ENGINE.run,$.STSR_ENGINE_SPEED);
this.status = 'on';
}
},
// Register process
add:function(fn,v){
if(!$.STSR_ENGINE_PROCESSES.inArray(fn)){
$.STSR_ENGINE_PROCESSES.push({'process':fn,'values':v});
}else{ return null; }
if($.STSR_ENGINE_PROCESSES.length>0) $.ENGINE.start();
},
//Unregister process
del:function(fn){
var l = $.STSR_ENGINE_PROCESSES.length;
var i = 0;
for (i; i<l; i++) {
if ($.STSR_ENGINE_PROCESSES[i]!=undefined && $.STSR_ENGINE_PROCESSES[i].process == fn)
{
$.STSR_ENGINE_PROCESSES.splice(i,1);
}
}
if($.STSR_ENGINE_PROCESSES.length<=0) {
$.ENGINE.stop();
}
},
die : function(){
if($.STSR_ENGINE_PROCESSES.length<=0 || !$.ENGINE || $.ENGINE==undefined) return false;
$.ENGINE.stop();
$.STSR_ENGINE_PROCESSES = [];
}
}
Array.prototype.inArray = function(needle) {
for(var i=0; i < this.length; i++){
if(this[ i].process === needle) return true;
}
return false;
}
Array.prototype.sortOn = function(){
var dup = this.slice();
if(!arguments.length) return dup.sort();
var args = Array.apply(null,arguments);
return dup.sort(function(a,b){
var props = args.slice();
var prop = props.shift();
while(a[prop] == b[prop] && props.length) prop = props.shift();
return a[prop] == b[prop] ? 0 : a[prop] > b[prop] ? 1 : -1;
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment