andy-h
3/16/2016 - 7:14 PM

Adds a timeout to a callback so that if the function isn't called within the timeout, the callback will be run anyway.

Adds a timeout to a callback so that if the function isn't called within the timeout, the callback will be run anyway.

function createFunctionWithTimeout(callback, opt_timeout){
	var called, timer;
	
	//if the function *isn't* called within the timeout, execute callback() anyway
	timer = setTimeout(function (){
			called = true;
			callback();
		}, opt_timeout || 1000);
	
	//if the function *is* called within the timeout, cancel the timer and execute callback()
	return function (){
		if(!called){
			clearTimeout(timer);
			callback();
		}
	}
}