thomasfrank.se

Dynamic Interval -- don't call too often

May 16, 2010

None of us JavaScripters want to choke our weblications with heavy code running in functions called repeatedly with setInterval.

Nevertheless this might happen once in a while, so what to do -- other than rewrite the whole code base, squeky clean and all event driven?

My dynamic interval setter to the rescue. This simple little script checks how long it takes to run your function and then adjusts the interval if needed. This lets you decide how many percent of total resources a function called by setDynamicInterval is allowed to hog -- to avoid going over that limit the interval will be prolonged. Here's how to use it:
The script (download, 1kb) that takes care of this is short:
setDynamicInterval=function(func,interval,percent){
	percent=percent||100;
	var f=function(){
		var me, timeTaken, startTime=new Date().getTime();
		me=arguments.callee;
		if(me.clearer.clear){return};
		func();
		timeTaken=new Date().getTime()-startTime;
		setTimeout(me,Math.max(interval-timeTaken,timeTaken*100/percent));
	};
	f.clearer={};
	f();
	return f.clearer
};

clearDynamicInterval=function(clearer){
	clearer.clear=true
};


I haven't used this in any real world projects yet, but I think it will work out fine. Functions in weblications under hard load tend to take a little longer to run. This will, hopefully, make all dynamic intervals prolong the time between calls -- thus helping to restore equilibrium in stressed out situations. And that's all a small script can ever hope for. ;-)
[comments]