How to terminate the script in JavaScript?
Asked Answered
S

26

253

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.

Selftaught answered 15/2, 2009 at 9:14 Comment(8)
Do you think you could expand on this requirement, exactly why are you trying to achieve this ?Saboteur
@andynormancx, this may be handy for debugging.Prosecution
just return; might be enough depending on your requirements, acts like die() with no parameters.Photocathode
why is always the first question 'why'?Leinster
SolutionEndogenous
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 simpleFlex
In node you just write process.exit(1), or other exit code you like.Tighten
@Tighten hooray for Node, but that's just one of the many possible ways of running an ECMAScript virtual machine... I believe that the OP implied a 'generic' version that works across every implementation, i.e. a built-in language construct/general-purpose function existing in all possible implementations. AFAIK, this does not exist.Fifi
A
95

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 '';
}
Avulsion answered 15/2, 2009 at 9:17 Comment(8)
Here's the source code of exit: kevin.vanzonneveld.net/techblog/article/…Wilds
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.Saboteur
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.Foregather
I think you did not include all events that should be handled, such as "selectstart" event.Force
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: https://mcmap.net/q/77005/-javascript-clear-all-timeoutsSpawn
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.Selfimportant
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://…Harms
why does javascript need such convoluted hacks for basic, basic functionality that should just exist?Pyromancy
P
118

"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
Popsicle answered 28/8, 2011 at 19:22 Comment(3)
@Sydwell : If you surround it by catch block, it will be caught and the program won't terminate, defying the point here.Podgy
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.Gabbro
@Podgy 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 :)Fruitcake
A
95

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 '';
}
Avulsion answered 15/2, 2009 at 9:17 Comment(8)
Here's the source code of exit: kevin.vanzonneveld.net/techblog/article/…Wilds
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.Saboteur
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.Foregather
I think you did not include all events that should be handled, such as "selectstart" event.Force
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: https://mcmap.net/q/77005/-javascript-clear-all-timeoutsSpawn
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.Selfimportant
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://…Harms
why does javascript need such convoluted hacks for basic, basic functionality that should just exist?Pyromancy
W
68

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.

Weep answered 28/9, 2011 at 14:12 Comment(3)
Excellent. Clean, simple, effective. Thanks!Galipot
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.Instrumentation
Instead of a return, comment the main call.Clod
K
26

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.

Keister answered 12/4, 2018 at 17:32 Comment(3)
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.Paratuberculosis
@Dan Expanding, or explaining, an acronym is definitely not any insult. The need to expand, or explain, an acronym depends on the individual reader. A reader who is unfamiliar with the acronym appreciates the explanation and finds the reading uninterrupted , whereas a reader who is familiar with the acronym becomes assured that the writer's intent of the acronym matches the reader's understanding.Portsalut
"There are many ways to exit a JS or Node script." What you mean is actually "There are many ways to exit a Node.js script." (a true statement). But there is JavaScript (or rather ECMAScript...) outside Node.js too, you know (and I'm not just assuming 'browsers' but rather all sorts of embedded ECMAScript VMs/interpreters). None of your solutions will work on them, of course.Fifi
V
23

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.

Vicereine answered 19/9, 2017 at 18:51 Comment(6)
window.fail isn't defined in current browsers.Estivate
That's the point - you could also do mikeyMouse; - the error will terminate. It's quick and dirty.Vicereine
Ah fair enough - maybe add that to your answer?Estivate
yes it could be helpful for people to know that you're just forcing a ReferenceError by calling an undefined variableMccallum
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)Flex
I'd vote that up if you also gave a way to do the same without throwing an error. :-)Fifi
C
12

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.

Certain answered 18/6, 2021 at 21:52 Comment(1)
Clearing timeouts combined with some of the other answers did the trick for me.Cathouse
H
9

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:

Honeysuckle answered 18/3, 2017 at 21:12 Comment(1)
That works... iff you're running JavaScript inside a browser which has debugging/developer tools. I can imagine that this will be true in 80-90% of the cases, but take into consideration that there are many, many ways to run ECMAScript outside a browser (well beyond Node.js as well!).Fifi
F
9

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; 
Fosse answered 11/4, 2020 at 20:4 Comment(0)
I
8

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)

Israelite answered 22/8, 2017 at 2:3 Comment(0)
T
5

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

Tarry answered 19/5, 2019 at 22:28 Comment(1)
This is the answer I needed. A simple button that stops execution: the Chrome debugger's Pause button.Pickax
L
4

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.");
Libelee answered 9/1, 2020 at 12:6 Comment(0)
O
2

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.

Olli answered 1/3, 2019 at 15:40 Comment(0)
R
1

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.

Rybinsk answered 15/2, 2009 at 9:27 Comment(3)
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.Saboteur
Not to mention, you don't need an extra bad function to throw an error. Javascript has a built-in throw statement.Elamite
The die function does a lot more than your p.blah(), it runs through the windows events and replaces the handles they have with "e.preventDefault();e.stopPropagation();", which will stop the events firing. Then it throws an exception.Saboteur
M
1

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)
Martensite answered 31/7, 2021 at 19:42 Comment(0)
O
0

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
Oxyacetylene answered 25/10, 2018 at 13:29 Comment(0)
S
0

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!!!');
Semolina answered 29/5, 2019 at 4:17 Comment(1)
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.');Russianize
U
0

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

Usn answered 3/7, 2020 at 14:11 Comment(0)
A
0

Wrapp with a function

(function(){
alert('start')

return;
alert('no exec')
})
Archetype answered 8/12, 2022 at 14:54 Comment(1)
Sorry, already answered before, but kudos for using an anonymous function!Fifi
F
0

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.

Functional approach

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.

Explicitly throwing an error

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

Implicitly forcing an error using something invalid

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!

  1. Using an invalid construct to break out of a script is really messy and sloppy. It's only good for code obfuscation and tricking the user who is trying to read it and gets baffled by the errors.
  2. It's not guaranteed that such behaviour will be observed by all ECMAScript-compliant environments (one example: Codepen correctly flags inexistent language constructs as errors and refuse to run the script).
  3. Even if it is now, it might not be the case in the future.
  4. When using third-party tools (some of which might not be immediately obvious, i.e. they're automatically being included without giving explicit notice to the JS programmer), there might exist something already named as 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!
  5. Unlike 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.
  6. Linters, syntax checkers, and other such automated tools will choke on this. This is especially true in projects using automated tools to check for errors and only publish "clean" code — as, say, any open-source solution published on GitHub/GitLab/Bitbucket/Gitea/whatever repository you use; or on essentially all internal programming tools of any software house worthy of its name.

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

JavaScript outside of the browser environment

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.

Fifi answered 15/4 at 21:48 Comment(0)
S
-1

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.

Stall answered 22/10, 2019 at 7:54 Comment(0)
P
-1

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

stopScript();
Pudgy answered 1/5, 2020 at 15:49 Comment(1)
Could you add a link to iobroker, please?Fifi
S
-2

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

Stoll answered 11/10, 2017 at 21:27 Comment(2)
This doesn't really answer the question. They're talking about a general problem, nothing to do with your specific SSE variables/file.Eocene
mjk - better now ?Stoll
L
-2

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.

Litterbug answered 25/12, 2018 at 5:10 Comment(1)
the question is the action, not the condition that triggers the action.Pyromancy
R
-3

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.

Rhizome answered 4/6, 2020 at 11:57 Comment(0)
P
-4

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>
Parisparish answered 6/12, 2020 at 8:22 Comment(6)
Just crashes the whole thing.Russianize
@Russianize 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.Parisparish
Does throw new Error('\r\n\r\nError Description:\r\nI\'m sorry Dave, I\'m afraid I can\'t do that.'); not work?Russianize
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.Russianize
@Russianize The infinite loop supersedes all executable libuv threads and runs until the stack is fully overflowed.Parisparish
So, why exactly is this a good idea?Fifi
L
-5

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.

Lilianaliliane answered 4/9, 2019 at 5:48 Comment(3)
It, however, gives the error in your linters as "Can't use 'return' outside of function"Bhopal
It stops execution because the statement is invalid. You could also use if (condition) { new new } or if (condition) { purpleMonkeyDishwasher(); }.Barnabas
Indeed, this is just another example of using invalid commands to trigger an error and stop execution.Fifi

© 2022 - 2024 — McMap. All rights reserved.