How can I exit the JavaScript script, much like PHP's exit or die?
I know it's not the best programming practice, but I need to.
"exit" functions usually quit the program or script, along with an error message supplied as a parameter. For example, die(...) in PHP:
die("sorry my fault, didn't mean to but now I am in byte nirvana")
The equivalent in JavaScript is to signal an error with the throw keyword, like this:
throw new Error();
You can easily test this:
var m = 100;
throw '';
var x = 100;
x
>>>undefined
m
>>>100
JavaScript equivalent for PHP's die. BTW it just calls exit() (thanks splattne):
function exit( status ) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brettz9.blogspot.com)
// + input by: Paul
// + bugfixed by: Hyam Singer (http://www.impact-computing.com/)
// + improved by: Philip Peterson
// + bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
// % note 1: Should be considered expirimental. Please comment on this function.
// * example 1: exit();
// * returns 1: null
var i;
if (typeof status === 'string') {
alert(status);
}
window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);
var handlers = [
'copy', 'cut', 'paste',
'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
];
function stopPropagation (e) {
e.stopPropagation();
// e.preventDefault(); // Stop for the form controls, etc., too?
}
for (i=0; i < handlers.length; i++) {
window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);
}
if (window.stop) {
window.stop();
}
throw '';
}
Even in simple programs without handles, events and such, it is best to put code in a main function, even when it is the only procedure:
<script>
function main()
{
// Code
}
main();
</script>
This way, when you want to stop the program you can use return.
main call.There are many ways to exit a JavaScript or Node.js script. Here are the most relevant:
// This will never exit!
setInterval((function() {
return;
}), 5000);
// This will exit after 5 seconds, with signal 1
setTimeout((function() {
return process.exit(1);
}), 5000);
// This will also exit after 5 seconds, and print its (killed) PID
setTimeout((function() {
return process.kill(process.pid);
}), 5000);
// This will also exit after 5 seconds and create a core dump.
setTimeout((function() {
return process.abort();
}), 5000);
If you're in the REPL (i.e., after running node on the command line), you can type .exit to exit.
If you don't care that it's an error, just write:
fail;
That will stop your main (global) code from proceeding. It is useful for some aspects of debugging/testing.
window.fail isn't defined in current browsers.mikeyMouse; - the error will terminate. It's quick and dirty.throw(message)JavaScript can be disabled in devtools: Ctrl + Shift + J followed Ctrl + Shift + P, and then type disable javascript or F12 → F1 → tick Disable JavaScript in the Debugger group.
Possible options that have been mentioned:
debugger; // Debugs JavaScript code as soon as entered
window.stop(); // Equivalent to the 'stop' button in the browser
throw new Error(); // Throws an error
window.location.reload(); // Reloads the current page
for(;;); // Crashes your browser
To deal with timeouts, Ajax, and events:
Clear all timeouts
var id = window.setTimeout(function() {}, 0);
while (id--) {
window.clearTimeout(id);
}
Abort DOM/XMLHttpRequest
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(i, jqXHR) {
jqXHR.abort();
$.xhrPool.splice(i, 1);
});
}
$.ajaxSetup({
beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); },
complete: function(jqXHR) {
var i = $.xhrPool.indexOf(jqXHR);
if (i > -1) $.xhrPool.splice(i, 1);
}
});
Remove all event listeners including inline
$("*").prop("onclick", null).off();
This removes scripts and recreates elements without events:
$('script').remove();
$('*').each(function(){
$(this).replaceWith($(this).clone());
});
If jQuery is not available on the webpage copy-paste the source code into a console.
Place the debugger; keyword in your JavaScript code where you want to stop the execution. Then open your favorite browser's developer tools and reload the page. Now it should pause automatically. Open the Sources section of your tools: the debugger; keyword is highlighted and you have the option to resume script execution.
More information is at:
There are multiple ways in JavaScript, and below are some of them:
Method 1:
throw new Error("Something went badly wrong!");
Method 2:
return;
Method 3:
return false;
Method 4:
new new
Method 5:
Write your custom function using the above method and call where you needed.
Note:
If you want to just pause the code execution, you can use:
debugger;
In my case I used window.stop.
The
window.stop()stops further resource loading in the current browsing context, equivalent to the 'stop' button in the browser.Because of how scripts are executed, this method cannot interrupt its parent document's loading, but it will stop its images, new windows, and other still-loading objects.
Usage:
window.stop();
(source)
window.stop()? Aye, if you're inside a browser. No, if you aren't.I think this question has been answered; click here for more information. Below is the short answer it is posted.
throw new Error("Stop script");
You can also use your browser to add breakpoints. Every browser is similar; check the information below for your browser.
For Chrome breakpoints information, click here
For Firefox breakpoints information click here
For Internet Explorer breakpoints information, click
For Safari breakpoints information, click here
If you just want to stop further code from executing without "throwing" any error, you can temporarily override window.onerror as shown in cross-exit:
function exit(code) {
const prevOnError = window.onerror
window.onerror = () => {
window.onerror = prevOnError
return true
}
throw new Error(`Script termination with code ${code || 0}.`)
}
console.log("This message is logged.");
exit();
console.log("This message isn't logged.");
window.onerror presumes that the script is running in a browser.In short: no, there is no way to exit/kill/terminate a running with the same semantics as implied by PHP's exit or die() (and, incidentally, almost all other programming languages out there).
Since the OP didn't specify where they're attempting to stop execution, one should not assume that they meant "in a browser" or "in Node.js" or even "in some application that embeds an ECMAScript virtual machine and/or interpreter" or, who knows, pure natively-compiled JavaScript using Nerd. Assuming either of those is naturally a possible environment for the OP, a full answer should attempt to encompass them all, and, if possible, even take into account future suggestions.
From the plethora of answers already given, I therefore point out to just a few; most answers will be a variant of those, with more or less bells & whistles, and possibly more detailed explanations.
This is essentially wrapping your code around a function and just use return to exit the function; there is nothing more to it.
The easiest example is by using an anonymous function, as suggested by @bellisario's answer:
(function () {
console.log('this code gets executed');
return;
console.log('this code is never reached');
})();
For browser environments, you might need to add this function as an event that gets launched when a page loads. Other environments might not even need that. Or you can make it a named function instead and call it explicitly, whatever you prefer (calling it main() would make a lot of sense due to its consistency with other programming languages in the C family).
Pros: It works under any environment. You cannot beat it in terms of "standard". No errors are thrown or logged to the console (unless you want to, doing it explicitly).
Cons: See the caveats pointed out by @bellisario.
console.log('this code gets executed');
throw new Error("<write here some reason for exiting>");
console.log('this code is never reached');
Pros: Should be universally available. Should also do whatever cleaning up is required.
Cons: As it says, it throws an error, which is not a "clean exit", so to speak. While the error message can be empty, most JS environments will still see it as an error and flag it accordingly. This might be especially annoying when a "clean" exit is required (because there is no further processing to do) but the user sees an unexpected "error" (even if the message is simply "this isn't an error; script terminated successfully!").
console.log('this code gets executed');
fail;
console.log('this code is never reached');
Instead of "fail" you can essentially use anything which doesn't exist in your code, even something like, you know... exit or die.
Pros: The code does not show an error, so programmers reading the code will not think of the construct as an "error".
Cons: Everything!
fail or exit or die or whatever was picked to cause the error, and this will give unpredictable results to the programmer (who is expecting execution to abort, not some unknown side-effects from using a function that they didn't know that had already been defined before). Granted, one may always rename one's invalid construct to something else, but it's not guaranteed that in the future the same won't happen again!throw new Error(...) — which is syntactically correct, even if semantically it might give the wrong notion (mathematically speaking, the absence of an error is also an error in itself; the "null error" if you wish, i.e. the error that is not part of the set of possible errors; however, such philosophical considerations are beyond the scope of this discussion) — each and every programmer will use a different invalid construct to break away from code (just look at the above answers, all of them using the same technique, but somehow those writing the answers seem unaware that they're all variants of the same concept...), which will make code written by different programmers next-to-impossible to maintain.So, very likely, this is the second worst possible approach (the worst I saw posted here was suggesting an infinite loop to avoid further code execution...).
Again, there is no universal standard there; but since it's likely that most JavaScript-out-of-the-browser is being run under Node.js, @not2qbit's answer should do the trick:
console.log('this code gets executed');
process.exit(0); // 0 means no error; 1 and greater signifies some sort of error.
console.log('this code is never reached');
Pros: This most closely resembles the way processes are (cleanly) exited under the C family of programming languages, and is therefore a familiar idiom.
Cons: Of course, it will only work under Node.js. Each implementation will have different ways of terminating the process (Deno, for instance, uses Deno.exit()). Granted, possibly this might throw an error on browser-based JavaScript as well (due to process being an inexistent object) and thus force the script to abort with an error, but, as mentioned before, that's hardly the best way to deal with it.
throw "";
Is a misuse of the concept but probably the only option. And, yes, you will have to reset all event listeners, just like the accepted answer mentions. You would also need a single point of entry if I am right.
On the top of it: You want a page which reports to you by email as soon as it throws - you can use for example Raven/Sentry for this. But that means, you produce yourself false positives. In such case, you also need to update the default handler to filter such events out or set such events on ignore on Sentry's dashboard.
window.stop();
This does not work during the loading of the page. It stops decoding of the page as well. So you cannot really use it to offer user a JavaScript-free variant of your page.
debugger;
Stops execution only with debugger opened. Works great, but not a deliverable.
To stop script execution without any error, you can include all your script into a function and execute it.
Here is an example:
(function () {
console.log('one');
return;
console.log('two');
})();
The script above will only log one.
Before use
If you use any undefined function in the script then script will stop due to "Uncaught ReferenceError". I have tried by following code and the first two lines executed.
I think, this is the best way to stop the script. If there's any other way then please comment. I also want to know another best and simple way. BTW, I didn't get the exit or die inbuilt function in JavaScript, like PHP, for terminating the script. If anyone know, then please let me know.
alert('Hello');
document.write('Hello User!!!');
die(); // Uncaught ReferenceError: die is not defined
alert('bye');
document.write('Bye User!!!');
throw new Error('\r\n\r\nError Description:\r\nI\'m sorry Dave, I\'m afraid I can\'t do that.');Wrap with a function:
(function() {
alert('start')
return;
alert('no exec')
})
If you want something similar to the PHP die() function, you could do:
function die(reason) {
throw new Error(reason);
}
Usage:
console.log("Hello");
die("Exiting script..."); // Kills script right here
console.log("World!");
The example above will only print "Hello".
I am using ioBroker and easily managed to stop the script with
stopScript();
This is an example, that, if a condition exist, then terminate the script. I use this in my SSE client-side JavaScript, if the
<script src="sse-clint.js" host="https://sse.host" query='["q1,"q2"]' ></script>
cannot be parsed right from the JSON parse...
if(!SSE_HOST) throw new Error(['[!] SSE.js: ERR_NOHOST - finished!']);
Anyway, the general idea is:
if(error == true) throw new Error(['You have this error', 'At this file', 'At this line']);
This will terminate/die your JavaScript script.
Simply create a BOOL condition. There isn’t any need for complicated code here..
If even once you turn it to true/ or multiple times, it will both give you one line of solution/not multiple. It is basically simple as that.
I use this piece of code to stop execution:
throw new FatalError("!! Stop JS !!");
You’ll get a reference error and the execution will be stopped. Regard the top voted answers here.
FatalError in JavaScript! Not as a built-in, at least. Unless, of course, you created your own class, deriving it from Error. In that case, please show us the code for that new class and how exactly it differs from the 'standard' Error (i.e., what additional functionality does it add to the base Error class which is new or different).This code will stop execution of all JavaScripts in current window:
for(;;);
Example
console.log('READY!');
setTimeout(()=>{
/* animation call */
div.className = "anim";
console.log('SET!');
setTimeout(()=>{
setTimeout(()=>{
console.log('this code will never be executed');
},1000);
console.log('GO!');
/* BOMB */
for(;;);
console.log('this code will never be executed');
},1000);
},1000);
#div {
position: fixed;
height: 1rem; width: 1rem;
left: 0rem; top: 0rem;
transition: all 5s;
background: red;
}
/* this <div> will never reached the right bottom corner */
#div.anim {
left: calc(100vw - 1rem);
top: calc(100vh - 1rem);
}
<div id="div"></div>
throw new... is what worked.It is not applicable in most circumstances, but I had lots of asynchronous scripts running in the browser, and as a hack I do
window.reload();
to stop everything.
I use a return statement instead of throw, as throw gives an error in the console. The best way to do it is to check the condition:
if(condition) {
return // Whatever you want to return
}
This simply stops the execution of the program from that line, instead of giving any errors in the console.
if (condition) { new new } or if (condition) { purpleMonkeyDishwasher(); }.
return;might be enough depending on your requirements, acts like die() with no parameters.returnfrom a function (as suggested here) is not a solution because there may follow other things that will occur after that and the programmer wants to cancel them! I think it's very simple