How to terminate the script in JavaScript?

461,343

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.

Share:
461,343

Related videos on Youtube

Nir
Author by

Nir

Updated on April 19, 2022

Comments

  • Nir
    Nir about 2 years

    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.

    • andynormancx
      andynormancx over 15 years
      Do you think you could expand on this requirement, exactly why are you trying to achieve this ?
    • SET001
      SET001 over 12 years
      @andynormancx, this may be handy for debugging.
    • Ishikawa
      Ishikawa about 9 years
      just return; might be enough depending on your requirements, acts like die() with no parameters.
    • Frungi
      Frungi about 6 years
      If you “need” it, you may be better off rethinking your design.
    • john ktejik
      john ktejik almost 6 years
      why is always the first question 'why'?
    • Bitterblue
      Bitterblue over 4 years
    • Apostolos
      Apostolos about 3 years
      The 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
    splattne over 15 years
    Here's the source code of exit: kevin.vanzonneveld.net/techblog/article/…
  • andynormancx
    andynormancx over 15 years
    That 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
    andynormancx over 15 years
    All 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
    annakata over 15 years
    the 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
    Chris over 15 years
    Not to mention, you don't need an extra bad function to throw an error. Javascript has a built-in throw statement.
  • ultimate
    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
    Andrew Swift almost 10 years
    Don'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
    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
    Ono Oogami about 8 years
    I think you did not include all events that should be handled, such as "selectstart" event.
  • skibulk
    skibulk almost 8 years
    You 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
    mjk over 6 years
    This doesn't really answer the question. They're talking about a general problem, nothing to do with your specific SSE variables/file.
  • kapad
    kapad over 6 years
    mjk - better now ?
  • John Greene
    John Greene over 6 years
    As 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
    Dan Dascalescu almost 6 years
    I 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
    mikemaccana about 5 years
    window.fail isn't defined in current browsers.
  • Marc
    Marc about 5 years
    That's the point - you could also do mikeyMouse; - the error will terminate. It's quick and dirty.
  • mikemaccana
    mikemaccana about 5 years
    Ah fair enough - maybe add that to your answer?
  • Frank Einstein
    Frank Einstein over 4 years
    Links 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
    Neithan Max over 4 years
    It, however, gives the error in your linters as "Can't use 'return' outside of function"
  • Coderer
    Coderer over 4 years
    It stops execution because the statement is invalid. You could also use if (condition) { new new } or if (condition) { purpleMonkeyDishwasher(); }.
  • ahnbizcad
    ahnbizcad almost 4 years
    the question is the action, not the condition that triggers the action.
  • ahnbizcad
    ahnbizcad almost 4 years
    why does javascript need such convoluted hacks for basic, basic functionality that should just exist?
  • StayCool
    StayCool over 3 years
    yes it could be helpful for people to know that you're just forcing a ReferenceError by calling an undefined variable
  • Apostolos
    Apostolos about 3 years
    For 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
    Ste about 3 years
    It 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
    Ste about 3 years
    Just crashes the whole thing.
  • DiD
    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
    Ste about 3 years
    Does throw new Error('\r\n\r\nError Description:\r\nI\'m sorry Dave, I\'m afraid I can\'t do that.'); not work?
  • Ste
    Ste about 3 years
    Well, 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
    DiD about 3 years
    @Ste The infinite loop supersedes all executable libuv threads and runs until the stack is fully overflowed.
  • Ralf
    Ralf almost 3 years
    Excellent. Clean, simple, effective. Thanks!
  • vauxhall
    vauxhall almost 3 years
    Clearing timeouts combined with some of the other answers did the trick for me.
  • John Deighan
    John Deighan over 2 years
    Works 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
    Timo almost 2 years
    Instead of a return, comment the main call.