Is it possible to stop JavaScript execution?

Short answer:

throw new Error("Something went badly wrong!");

If you want to know more, keep reading.


Do you want to stop JavaScript’s execution for developing/debugging?

The expression debugger; in your code, will halt the page execution, and then your browser’s developer tools will allow you to review the state of your page at the moment it was frozen.

Do you want to stop your application arbitrarily and by design?

On error?

Instead of trying to stop everything, let your code handle the error. Read about Exceptions by googling. They are a smart way to let your code “jump” to error handling procedures without using tedious if/else blocks.

After reading about them, if you believe that interrupting the whole code is absolutely the only option, throwing an exception that is not going to be “caught” anywhere except in your application’s “root” scope is the solution:

// creates a new exception type:
function FatalError(){ Error.apply(this, arguments); this.name = "FatalError"; }
FatalError.prototype = Object.create(Error.prototype);

// and then, use this to trigger the error:
throw new FatalError("Something went badly wrong!");

be sure you don’t have catch() blocks that catch any exception; in this case modify them to rethrow your "FatalError" exception:

catch(exc){ if(exc instanceof FatalError) throw exc; else /* current code here */ }

When a task completes or an arbitrary event happens?

return; will terminate the current function’s execution flow.

if(someEventHappened) return; // Will prevent subsequent code from being executed
alert("This alert will never be shown.");

Note: return; works only within a function.

In both cases…

…you may want to know how to stop asynchronous code as well. It’s done with clearTimeout and clearInterval. Finally, to stop XHR (Ajax) requests, you can use the xhrObj.abort() method (which is available in jQuery as well).

Leave a Comment