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:
	var f=function(){
		var me, timeTaken, startTime=new Date().getTime();
		timeTaken=new Date().getTime()-startTime;
	return f.clearer


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. ;-)