﻿/*	Create an instance of this to wait for an asynchronous call to finish and then execute other statements 
		waitFor : reference to function returning a boolean when said call is done
		whileWaiting : reference to function to execute when waiting for completion - no heavy computations please!
		whenDone : reference to function to execute	when call is completed
		ms : interval in milliseconds between each check for completion
*/
function waitForIt() {
	var self = this;

	this.ms = 100;
	this.waitFor = null;
	this.whileWaiting = null;
	this.whenDone = null;

	this.run = function() {
		if (typeof self.waitFor == "function") {
		
			//Call has been completed:
			if (self.waitFor()) {
				//Execute our "cleanup" function, if any:
				if (typeof self.whenDone == "function") {
					self.whenDone();
				}

				//Clear timeout:
				self.cancel();
			}
			//Call is incomplete:
			else {
			
				//Do what needs to be done while waiting:
				if (typeof self.whileWaiting == "function") {
					self.whileWaiting();
				}

				//Set timeout:
				self.timeoutID = window.setTimeout( function() {
					self.run();
					}, self.ms);
			}
		}
		else {
			self.cancel();
		}
	}

	//Clear our timeout, if any:
	this.cancel = function() {
		if (typeof self.timeoutID == "number") {
			window.clearTimeout(self.timeoutID);
			delete self.timeoutID;
		}
	}
}

