Question

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.

Was it helpful?

Solution

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 '';
}

OTHER TIPS

"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

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".

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.

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.

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.

I hope it helps.

More information at:

In my case I used the window.stop API which is like clicking the X button on your browser:

window.stop();

This answer provides details demonstrating extra framework that will help solve this and other early exit, exceptions, process control, and sequential function handling needs in modular javascripts. Solution provides closure examples. This answer assumes that the individual would like other scripts on the page to continue to run after the script in question has exited.

Live example of simple solution here: https://jsfiddle.net/alignedfibers/cpe1o1yy/66/

<script>
    var safetyRun = (function(){
      var curExecution = null;
      var exceptionHandlers = {
        cleanup:function(){
          /*do exit cleanup*/
          console.log("Cleanup could set straglers to {}");
          return;
        }
      }
      var exitErr = function(errcode){
        curExecution.exNames.push("cleanup");
        throw new Error("EarlyExit");
      }
        var run = function(fun){
          curExecution = this;
          curExecution.exNames = [];
          fun(exitErr);
          for ( x in exNames){
            exceptionHandlers[x]();
          }
          return;
        }
        return run;
    })();
    var exitThisScript = function(exit){
      //write some modular code
      console.log("before exit");
      exit();
      console.log("after exit");
      return;
    }
    safetyRun(exitThisScript);
</script>

Above is a "CallRunner" that provides a very simple way to exit for free just by passing your function to the runner.

The variable naming in the fiddle may be confusing, the function named "fun" is the name used within safetyRun to reference the function we are trying to exit, and exitErr is the name used to reference the function we run to actually complete the exit. Also a little confusing is: once the exitErr completes, the stack frame still is not released from the thread of control that called the function that we exited. Because we still have thread of control we can use functions or error codes pushed on to an array in the exitErr function and call them itteratively before returning to allow any other functions to run. This is allowing us to change any weights or make corrections or set any state needed that we can use to alert what error correction states need attention, send a log report or even complete challenging cleanup and autonomously fix the function in the background and itteratively call exitErr until it completes a return instead of a throw thus allowing the function we are trying to exit early complete, (suggest doing this offmainthread). This "wrapper/harness" could be a good way to verify browser versions and stuff at the start of a function, you could even do a static or dynamic import here if you manage your own libraries or what ever you can really think of. Exit is only one fundemental function that can be made available for your function by wrapping it like this.

The code in the fiddle is a little dirty and not pretty, new es6 constructs can make this prettier. In addition I recommend that you call a harness generator at the top of this function and assign its result to a local var so the function you want to exit can look more like the code below. In order to keep thread of control without releasing the stack, you will still need need to have a harness.run(function(harness){/MyVanillaFunc/}) to wrap your vanilla function, otherwise the below in theory should work. Wrapping is exactly what I did in the exitEarly code above.

var rockStarFunction = new function (){
var harness = reducePublicStrapOnFromCache()._url(location);
return function(){ /*wrapper would wrap these internals*/
        harness.scriptContextChangeEvent();
        harness.imInteligentFunction("{slib_err-15346 : 'Cannot handle request, ::suggest(mesh//abc) exit back to pool'}");
        harness.exit();
        console.log("You should never get this far");
        return true;
    };
}

The solution I have provided here is the one I recommend if your intention is to build a javascript runner container with capabilities such as exit, assert, mock and the such built in. I think this is the better way to build this containership and make my functions transmittable.

If you're looking for a way to forcibly terminate execution of all Javascript on a page, I'm not sure there is an officially sanctioned way to do that - it seems like the kind of thing that might be a security risk (although to be honest, I can't think of how it would be off the top of my head). Normally in Javascript when you want your code to stop running, you just return from whatever function is executing. (The return statement is optional if it's the last thing in the function and the function shouldn't return a value) If there's some reason returning isn't good enough for you, you should probably edit more detail into the question as to why you think you need it and perhaps someone can offer an alternate solution.

Note that in practice, most browsers' Javascript interpreters will simply stop running the current script if they encounter an error. So you can do something like accessing an attribute of an unset variable:

function exit() {
    p.blah();
}

and it will probably abort the script. But you shouldn't count on that because it's not at all standard, and it really seems like a terrible practice.

EDIT: OK, maybe this wasn't such a good answer in light of Ólafur's. Although the die() function he linked to basically implements my second paragraph, i.e. it just throws an error.

UPDATE: This works as long as you don't catch it!

throw window.location.assign('dead.html');

This little function comes pretty close to mimicking PHP's exit(). As with the other solutions, don't add anything else.

function exit(Msg)
    {
    Msg=Msg?'*** '+Msg:'';
    if (Msg) alert(Msg);
    throw new Error();
    } // exit

Simply create a BOOL condition , no 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 - basically simple as that.

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.

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 used your browser to add break points, every browser is similar, check info below for your browser.

For Chrome break points info click here
For Firefox break points info click here
For Explorer break points info click
For Safari break points info click here

If you use any undefined function in the script then script will stop due to "Uncaught ReferenceError". I have tried by following code and first two lines executed.

I think, this is the best way to stop the script. If there's any other way then please comment me. I also want to know another best and simple way. BTW, I didn't get exit or die inbuilt function in Javascript like PHP for terminate 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!!!');

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>

canot be parsed right from 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 javasript script

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top