/*	VERSION:  2.0	

USAGE:
	#include "functions/avoidLoopPanic.as"
	
	// optional
	if(!_global.AVOID_LOOP_PANIC)		_global.AVOID_LOOP_PANIC = make_avoidLoopPanic( 2 );
	
	for(var i=0; i<3000; i++){
		AVOID_LOOP_PANIC( function(){
			stress( param );
		} );// let's stay cool()
	}// for:  a ridiculous loop
	
DESCRIPTION:
	Prevents Flash from crashing when a crazy amount of functions are called at once.
	ONLY use this for functions that don't need to run right away, and don't have other things relying on them.
*/
function make_avoidLoopPanic( additionalCalls ){
	if( isNaN(additionalCalls) )		additionalCalls = 0;
	var callInc = 4 + additionalCalls;
	//var callInc = 6 + additionalCalls;
	var thresh = Math.floor(256 / callInc);
	
	var calls = 0;
	var func_list = [];
	return function( func ){
		trace("AVOID_LOOP_PANIC()");
		// add this function + with included params listed after it
		func_list.push( func );
		
		// decide whether to call now,  or wait
		calls ++;
		if(calls < thresh){
			// remove the 1st function, and call it
			func_list.shift()();
		}
		else
		{// if:  time to wait
			// luckily, this only runs once when "calls" gets too high
			setTimeout(function(){
				// luckily, this also only gets called once when "calls" gets too high
				calls = 0;
				func_list.shift()();
			}, 0);
		}// if:  time to wait
	}// return()
}// make_avoidLoopPanic()
if(!_global.AVOID_LOOP_PANIC)		_global.AVOID_LOOP_PANIC = make_avoidLoopPanic();