Is it possible in some way to stop or terminate JavaScript in a way that it prevents any further JavaScript-based execution from occuring, without reloading the browser?
I am thinking of a JavaScript equivalent of exit()
in PHP.
To stop the execution of a function in JavaScript, use the clearTimeout() method.
If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch . If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err) .
If you're in the REPL (i.e. after running node on the command line), you can type . exit to exit.
Short answer:
throw new Error("Something went badly wrong!");
If you want to know more, keep reading.
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.
Instead of trying to stop everything, let your code handle the error. Read about Exception
s 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 */ }
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.
...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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With