How to terminate the script in JavaScript?
Solution 1
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 '';
}
Solution 2
"exit" functions usually quit the program or script along with an error message as paramete. For example die(...) in php
die("sorry my fault, didn't mean to but now I am in byte nirvana")
The equivalent in JS 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
Solution 3
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
.
Solution 4
If you don't care that it's an error just write:
fail;
That will stop your main (global) code from proceeding. Useful for some aspects of debugging/testing.
Solution 5
There are many ways to exit a JS or Node 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.
Related videos on Youtube
Nir
Updated on April 19, 2022Comments
-
Nir about 2 years
How can I exit the JavaScript script much like PHP's
exit
ordie
? I know it's not the best programming practice but I need to.-
andynormancx over 15 yearsDo you think you could expand on this requirement, exactly why are you trying to achieve this ?
-
SET001 over 12 years@andynormancx, this may be handy for debugging.
-
Ishikawa about 9 yearsjust
return;
might be enough depending on your requirements, acts like die() with no parameters. -
Frungi about 6 yearsIf you “need” it, you may be better off rethinking your design.
-
john ktejik almost 6 yearswhy is always the first question 'why'?
-
Bitterblue over 4 years
-
Apostolos about 3 yearsThe question is very simple and clear: it says "terminate the script". This means that the script is over. Finished. No more things should be expected to happen after that. It doesn't mean just "terminate a function". A
return
from 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
-
-
splattne over 15 yearsHere's the source code of exit: kevin.vanzonneveld.net/techblog/article/…
-
andynormancx over 15 yearsThat code doesn't appear to stop events on elements from firing, just the window's events. So you'd also need to loop through all the elements on the page doing something similar. It all sounds like a very odd requirement though.
-
andynormancx over 15 yearsAll that will do will stop the current executing bit of scripting. It won't stop new events from firing and running new bits of script.
-
annakata over 15 yearsthe whole die concept is a bit broken - the flow should be capable of handling any and all eventualities, whether that reqire try-catch or not.
-
Chris over 15 yearsNot to mention, you don't need an extra bad function to throw an error. Javascript has a built-in throw statement.
-
ultimate about 10 years@Sydwell : If you surround it by catch block, it will be caught and the program won't terminate, defying the point here.
-
Andrew Swift almost 10 yearsDon't forget that you can add a message to the error: throw new Error('variable ='+x); It's a nice way to quickly end a script while you're working on it and get the value of a variable.
-
jave.web about 9 years@ultimate I think that #Sydwell ment to wrap the whole script in try/catch, so you can get a) clean exit b) possible exception message when needed :) Throwing uncought exceptions generally does not bring any good :)
-
Ono Oogami about 8 yearsI think you did not include all events that should be handled, such as "selectstart" event.
-
skibulk almost 8 yearsYou can't stop XMLHttpRequest handlers. The current code does not stop intervals or timeouts from executing. Demo: jsfiddle.net/skibulk/wdxrtvus/1 You might consider this as a fix: stackoverflow.com/a/8860203/6465140
-
mjk over 6 yearsThis doesn't really answer the question. They're talking about a general problem, nothing to do with your specific SSE variables/file.
-
kapad over 6 yearsmjk - better now ?
-
John Greene over 6 yearsAs of Google Chrome v62.0.3202.94 and Firefox v52.2.0, the window.addEventListener function now reports to the browser console as: "Use of Mutation Events is deprecated. Use MutationObserver instead." No idea what the workaround is.
-
Dan Dascalescu almost 6 yearsI didn't want to insult the intelligence of the readers by explaining an acronym that shows up as the first result of Googling it. I suggest you don't mix JavaScript code with REPL commands because if a user copy/pastes that code block and runs it, they'll get a Syntax error on the ".exit" line.
-
mikemaccana about 5 years
window.fail
isn't defined in current browsers. -
Marc about 5 yearsThat's the point - you could also do
mikeyMouse;
- the error will terminate. It's quick and dirty. -
mikemaccana about 5 yearsAh fair enough - maybe add that to your answer?
-
Frank Einstein over 4 yearsLinks of Exit.js are both dead but I've been able to find a backup on archive.org. So, just in case someone needs it... web.archive.org/web/20091002005151/http://…
-
Neithan Max over 4 yearsIt, however, gives the error in your linters as "Can't use 'return' outside of function"
-
Coderer over 4 yearsIt stops execution because the statement is invalid. You could also use
if (condition) { new new }
orif (condition) { purpleMonkeyDishwasher(); }
. -
ahnbizcad almost 4 yearsthe question is the action, not the condition that triggers the action.
-
ahnbizcad almost 4 yearswhy does javascript need such convoluted hacks for basic, basic functionality that should just exist?
-
StayCool over 3 yearsyes it could be helpful for people to know that you're just forcing a ReferenceError by calling an undefined variable
-
Apostolos about 3 yearsFor debugging purposes (because otherwise you don't care), if one is to exit in a quick and "dirty" way, then better show a (recognizable) message with
throw(message)
-
Ste about 3 yearsIt does terminate the rest of the code but with this at least you can give it an error message.
throw new Error('\r\n\r\nError Description:\r\nI\'m sorry Dave, I\'m afraid I can\'t do that.');
-
Ste about 3 yearsJust crashes the whole thing.
-
DiD about 3 years@Ste Sometimes, when you need to stop the execution of the script outside the current control flow, or stop all WebWorkers working in different obfuscated scripts connected to the current page, with only console and 10 seconds to think, there is no alternative solution.
-
Ste about 3 yearsDoes
throw new Error('\r\n\r\nError Description:\r\nI\'m sorry Dave, I\'m afraid I can\'t do that.');
not work? -
Ste about 3 yearsWell, this is cool! I guess my environment didn't like it and crashed. It's a windows app and not web-based.
throw new...
is what worked. -
DiD about 3 years@Ste The infinite loop supersedes all executable libuv threads and runs until the stack is fully overflowed.
-
Ralf almost 3 yearsExcellent. Clean, simple, effective. Thanks!
-
vauxhall almost 3 yearsClearing timeouts combined with some of the other answers did the trick for me.
-
John Deighan over 2 yearsWorks if you're a poor programmer and don't break your code into other functions. If you do, then a return inside a function that's inside a function won't do what you want.
-
Timo almost 2 yearsInstead of a return, comment the
main
call.