How to terminate the script in JavaScript?

JavascriptExitDie

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

"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 2 - Javascript

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 3 - Javascript

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 - Javascript

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 - Javascript

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.

Solution 6 - Javascript

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:

Solution 7 - Javascript

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)

Solution 8 - Javascript

Javascript can be disabled in devtools: ctrl+shift+j followed cltf+shift+p then type disable javascript

Possible options that mentioned above:

window.stop(); // equivalent to the 'stop' button in the browser
debugger; // debugs
for(;;); // crashes your browser
window.location.reload(); // reloads current page

If page is loaded and you don't want to debug crash or reload:

throw new Error();

Additionally 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 source code into a console.

There're might be other stuff. Let me know in a comment.

Solution 9 - Javascript

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

Solution 10 - Javascript

In JavaScript multiple ways are there, 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 use above method and call where you needed

Note: If you want to just pause the code execution you can use

debugger; 

Solution 11 - Javascript

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.

Solution 12 - Javascript

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.

Solution 13 - Javascript

I know this is old, but if you want a similar 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".

Solution 14 - Javascript

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

Solution 15 - Javascript

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!!!');

Solution 16 - Javascript

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

Solution 17 - Javascript

I am using iobroker and easily managed to stop the script with

stopScript();

Solution 18 - Javascript

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>

Solution 19 - Javascript

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 need to read a function of your script outside of the script itself, remember that (normally) it doesn't work: to do it, you need to use a pre-existing variable or object (you can put your function in the window object).
  • The above code could be what you don't want: put an entire script in a function can have other consequences (ex. doing this, the script will run immediately and there isn't a way to modify its parts from the browser in developing, as I know, in Chrome)

Solution 20 - Javascript

Not applicable in most circumstances, but I had lots of async scripts running in the browser and as a hack I do

window.reload();

to stop everything.

Solution 21 - Javascript

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

Solution 22 - Javascript

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.

Solution 23 - Javascript

i use this piece of code to stop execution:

throw new FatalError("!! Stop JS !!");

you will get a console error though but it works good for me.

Solution 24 - Javascript

i use return statement instead of throw as throw gives error in 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNirView Question on Stackoverflow
Solution 1 - JavascriptLorenz Lo SauerView Answer on Stackoverflow
Solution 2 - JavascriptÓlafur WaageView Answer on Stackoverflow
Solution 3 - JavascriptJhepView Answer on Stackoverflow
Solution 4 - JavascriptMarcView Answer on Stackoverflow
Solution 5 - Javascriptnot2qubitView Answer on Stackoverflow
Solution 6 - JavascriptrbelowView Answer on Stackoverflow
Solution 7 - JavascriptMusaView Answer on Stackoverflow
Solution 8 - JavascriptHebeView Answer on Stackoverflow
Solution 9 - JavascriptalfmoncView Answer on Stackoverflow
Solution 10 - JavascriptSrikrushnaView Answer on Stackoverflow
Solution 11 - JavascriptDavid ZView Answer on Stackoverflow
Solution 12 - Javascriptinformatik-handwerk.deView Answer on Stackoverflow
Solution 13 - JavascriptNanooView Answer on Stackoverflow
Solution 14 - JavascriptDavid SpectorView Answer on Stackoverflow
Solution 15 - JavascriptnpsinghView Answer on Stackoverflow
Solution 16 - JavascriptRichie BendallView Answer on Stackoverflow
Solution 17 - Javascriptuser13449123View Answer on Stackoverflow
Solution 18 - JavascriptDiDView Answer on Stackoverflow
Solution 19 - JavascriptBellisarioView Answer on Stackoverflow
Solution 20 - JavascriptM3RSView Answer on Stackoverflow
Solution 21 - JavascriptkapadView Answer on Stackoverflow
Solution 22 - JavascriptmoniView Answer on Stackoverflow
Solution 23 - Javascriptjohn SmithView Answer on Stackoverflow
Solution 24 - JavascriptgraykraftView Answer on Stackoverflow