Navigation

Javascript Exit Alert

Here are two JavaScript functions that any developer would find useful during script debugging.

The first function is used to exit script execution. Not only this function works both inside functions and within global scope but it will also prevent any other script from executing after it. This effect is achieved by simply throwing an uncaught exception, thus, causing the browser to elegantly drop all following script execution and log a 'Script Exit' error (note that not all browsers will log the actual error text, some will just log an "uncaught exception").

function exit ()
{
	throw ('Script Exit');
}
The second function is what I like to call the debugging version of alert. This function will display a message and present two option, OK and Cancel. Clicking the OK button will continue script execution (same as alert), clicking the Cancel button will exit script execution using the exit function above. This is especially useful when debugging looping code, which would otherwise cause browser window locks/hangs by spamming the alert box.

function alertDebug (msg)
{
	if (!confirm (msg + '\n\n Click OK to continue, Cancel to stop script execution.'))
		exit ();
}
That's it. I hope you find those two tiny functions useful, and please feel free to leave your feedback in the comments section below.