376

Is it possible in some way to stop or terminate JavaScript in a way that it prevents any further JavaScript-based execution from occuring, without reloading the browser?

I am thinking of a JavaScript equivalent of exit() in PHP.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Industrial
  • 41,400
  • 69
  • 194
  • 289
  • 11
    return - inside a function – mplungjan Feb 15 '12 at 18:11
  • 1
    Dup of http://stackoverflow.com/questions/550574/how-to-terminate-the-script-in-javascript ? – Dewi Morgan Aug 10 '15 at 00:25
  • 7
    `debugger;` to freeze all javascript loops of a page. Very useful to kill annoying javascript, especially when the page requires javascript to load. – loxaxs Dec 28 '17 at 23:24
  • 2
    `debugger` is great for halting a page from loading when there is lots of asynchronous stuff going on, but it would be nice if one could get rid of the translucent gray overlay and scroll/use the page at the same time. Anyone know how to do that? – Michael Altfield Jun 15 '21 at 20:00
  • @MichaelAltfield I came here for the exact reason because web page like quora which pops up a registration overlay to force people sign in. I'd like to skip it, even if I need to do it manually every time. Have you found a solution yet? – oldpride Oct 19 '22 at 14:45

11 Answers11

644

Short answer:

throw new Error("Something went badly wrong!");

If you want to know more, keep reading.


Do you want to stop JavaScript's execution for developing/debugging?

The expression debugger; in your code, will halt the page execution, and then your browser's developer tools will allow you to review the state of your page at the moment it was frozen.

Do you want to stop your application arbitrarily and by design?

On error?

Instead of trying to stop everything, let your code handle the error. Read about Exceptions by googling. They are a smart way to let your code "jump" to error handling procedures without using tedious if/else blocks.

After reading about them, if you believe that interrupting the whole code is absolutely the only option, throwing an exception that is not going to be "caught" anywhere except in your application's "root" scope is the solution:

// creates a new exception type:
function FatalError(){ Error.apply(this, arguments); this.name = "FatalError"; }
FatalError.prototype = Object.create(Error.prototype);

// and then, use this to trigger the error:
throw new FatalError("Something went badly wrong!");

be sure you don't have catch() blocks that catch any exception; in this case modify them to rethrow your "FatalError" exception:

catch(exc){ if(exc instanceof FatalError) throw exc; else /* current code here */ }

When a task completes or an arbitrary event happens?

return; will terminate the current function's execution flow.

if(someEventHappened) return; // Will prevent subsequent code from being executed
alert("This alert will never be shown.");

Note: return; works only within a function.

In both cases...

...you may want to know how to stop asynchronous code as well. It's done with clearTimeout and clearInterval. Finally, to stop XHR (Ajax) requests, you can use the xhrObj.abort() method (which is available in jQuery as well).

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 19
    Note: All remaining asynchronous functions like `setTimeout` or `XMLHttpRequest` will still execute. Currently there is no *standard* way to completely terminate JavaScript. – Derek 朕會功夫 Jul 17 '13 at 22:01
  • 9
    If you need to stop the whole JS process for debugging purposes, use the Developer Tools in Webkit or Firebug on Firefox to set breakpoints by doing `debugger;`. This will halt absolutely everything from executing. – Derek 朕會功夫 Jul 17 '13 at 22:03
  • @gattsbr Doesn't that still cause the next lines to be immediately executed? – Kevin Dice May 24 '14 at 11:47
  • 5
    +1 for the `debugger;` statement. `return` outside functions produces syntax error (just to make clear for surfers). There are so many aspects to consider... I was just successful by embracing the part I didn't want to be executed with `if (false) { ... }`. So you don't have to care about nested comments. – peter_the_oak Aug 18 '14 at 12:53
  • For me I just wanted to using `return;` worked just fine (within a jquery event handler). – Andrew Aug 19 '15 at 14:37
  • Like `debugger;` option, but don't like how the script continues after you finish inspecting variables and such. So another option is to use both: `debugger; throw new Error();` – Andrew Mar 21 '17 at 19:16
  • I am instantiating a complex JS object in a Jasmine unit test, I test a bunch of the object's methods and then when I'm done I want to stop the avalanche of events, ajax calls, library calls that this main object has triggered. I haven't found a good way to do this at the moment. – Costin_T Aug 10 '17 at 14:17
  • Since the scope of `throw` is to throw exceptions and not stopping functions execution, and then this usage is out of its scope, isn't this a bad practice? – Salvatore Aug 04 '18 at 08:10
  • 2
    @Derek朕會功夫 `debugger` is great for halting a page from loading when there is lots of asynchronous stuff going on, but it would be nice if one could get rid of the translucent gray overlay and scroll in the page at the same time. – Michael Oct 31 '18 at 17:09
  • @Michael You can’t scroll because the debugger is blocking the rendering thread. You can pause the thread with a debugger but you can’t stop code execution with it, not to mention you don’t have access to the devtool in your JS code. – Derek 朕會功夫 Oct 31 '18 at 17:12
  • I have been working with JS for a year and **I have only discovered `debugger` today! Thank you!** – Shark Lasers Feb 11 '20 at 14:21
  • best one are; `return false;` `return 0;` or simply write `return;` this will exit the execution. – NomanJaved May 14 '20 at 13:28
  • Beware. This doesnt work for unload events and other similar events. – David Lannan May 24 '20 at 05:24
151

You can make a JavaScript typo :D (thinking outside the box here)

thisFunctionDoesNotExistAndWasCreatedWithTheOnlyPurposeOfStopJavascriptExecutionOfAllTypesIncludingCatchAndAnyArbitraryWeirdScenario();

Or something like:

new new
Bart Calixto
  • 19,210
  • 11
  • 78
  • 114
  • 5
    I was trying to intercept objects in the middle of asynchronous JS, which is wrapped into catch-every-exception and redirect without any option to stop all async's manually or change catch/redirect part. Writing `abcd` helped: script compiles but falls here with 'not defined' runtime error! Thanks a lot, this should be the answer. – Rast Aug 28 '14 at 18:16
  • 20
    From now on, i will include this function in everything that i write, let the meme be created! – v010dya May 04 '15 at 13:47
  • 2
    Just make sure to explain this line in your code. If someone after you see this line, he will be confused as hell :) – mokiSRB Feb 10 '16 at 14:59
  • I don't think anyone intend to leave a line like this on the code. It's only useful while debugging – Bart Calixto Feb 11 '16 at 11:19
  • 6
    This doesn't quite work while using JavaScript as a scripting language. The running agent catches it as a run time error and won't advance until you change it to a function (that exists) call or throw an error. Great idea, though. Also, thought you should probably camel case it so it doesn't need to be commented in the event you actually want it to stick around. Something like this, I think: `fakeFunctionThatEffectivelyStopsAllProcessingInJavaScript();`. Thanks. – CSS Feb 11 '16 at 22:11
  • 4
    Now that is thinking outside the box. Syntax errors on purpose! – ahyattdev Oct 31 '16 at 23:46
  • 1
    +1 Also related: [debugger ignores previous function call](http://stackoverflow.com/questions/42037733/debugger-ignores-previous-function-call) – akinuri Feb 04 '17 at 07:30
  • 2
    hats-off ... from a man who doesnt wear any hats :) best answer since slice bread :) – Amarsh Oct 20 '18 at 00:52
  • My method has been `eval("*");` for now – 0xLogN Mar 22 '23 at 00:10
  • This answer helped me with [this problem](https://stackoverflow.com/questions/76852307/javascript-redirect-is-getting-hijacked-and-it-is-not-onbeforeunload-event). Pushing this to production. – Vanity Slug - codidact.com Aug 08 '23 at 16:12
39

Something like this might work:

function javascript_abort()
{
   throw new Error('This is not an error. This is just to abort javascript');
}

Taken from here:

http://vikku.info/codesnippets/javascript/forcing-javascript-to-abort-stop-javascript-execution-at-any-time/

Mikey G
  • 3,473
  • 1
  • 22
  • 27
  • 1
    Is that part of the ECMA standard or a browser extension? – DanMan Mar 19 '13 at 15:44
  • Do you mean does this function already exist in js, or do you have to add it? If so, you have to add it in whatever scope you want to call it from. – Mikey G Mar 22 '13 at 13:47
  • I mean the `Error` object. – DanMan Mar 22 '13 at 16:56
  • This can tell you more than I know about it: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error – Mikey G Mar 22 '13 at 18:01
  • 2
    http://www.ecma-international.org/ecma-262/5.1/#sec-15.11 – DanMan Mar 22 '13 at 21:01
  • hehehe... this is crazy and beautiful! Crazy because I never would have thought that I'd need to do it... but I had to use it right now over here in a peculiar situation: https://github.com/vakata/jstree/issues/777 – Leniel Maccaferri Jul 29 '14 at 17:42
  • I know I'm late to this party, but I found your answer very useful for halting my QUnit tests. I can copy a test that's failing to the top of the code and then call `javascript_abort()` after it executes. It's an easy way to save the execution time of the balance of the tests. And it saves me from commenting and uncommenting a lot of tests and potentially screwing things up. Thanks. – Karl Sep 27 '15 at 19:06
31

I do:

setTimeout(function() { debugger; }, 5000)

this way I have 5 seconds to interact with UI and then in stops. Las time I used was when I needed to leave custom tooltip visible, to do some styling changes.

user2846569
  • 2,752
  • 2
  • 23
  • 24
  • 1
    FYI, chrome dev tools allows you to toggle ":hover" on elements for such scenarios – Tom Teman Sep 26 '16 at 09:30
  • 1
    ":hover" is css thing, if you show tooltip with mouseover() for example, this doesn't help – user2846569 Sep 26 '16 at 09:54
  • 3
    This is (almost) the only answer that fulfills the "in a way that it prevents any further JavaScript-based execution from occuring" clause in the question. However, It is missing the information that it only works when the developer console is open, the timeout is not necessary, and that it can be manually resumed (it's a pause rather than a stop). – Hockey Dec 18 '16 at 02:36
  • This still doesnt work on unload and onbefore events. Just beware that there is likely no "simple" global solution for this, unless you manually control the debugger yourself. – David Lannan May 24 '20 at 05:27
27

No.

Even if you throw an exception, it will only kill the current event loop. Callbacks passed to setTimeout or DOM/XMLHttpRequest event handlers will still run when their time comes.

Stephen Schwink
  • 512
  • 4
  • 7
  • 7
    How can we prevent that? – Jikku Jose Jul 17 '15 at 09:27
  • 4
    I made a test for timeouts before I read your post. It confirms that an exception will not terminate a timout. https://jsfiddle.net/skibulk/wdxrtvus/ – skibulk Apr 28 '16 at 15:46
  • 1
    You might consider this to clear timeouts and intervals: stackoverflow.com/a/8860203/6465140 – skibulk Aug 09 '16 at 16:36
  • 1
    This is interesting, so we could say that every single person who says "exceptions halt program execution" is wrong, instead, they should all say "exceptions halt the execution of the current event loop entry". – doubleOrt Jan 21 '18 at 17:35
24

I am using

return false;

if I want to abort from JavaScript from running further downwards.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TonyTony
  • 1,344
  • 15
  • 23
14

If you're in a function you can exit it using return; but that doesn't stop execution of the parent function that called that function.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
10

You can call return early in a function, and at least that function will stop running. You can also just use throw '' to cause an error and stop the current process. But these won't stop everything. setTimeout and setInterval can make delayed functions and functions that run on a time interval, respectively. Those will continue to run. Javascript events will also continue to work as usual.

benekastah
  • 5,651
  • 1
  • 35
  • 50
5

I know this is old, but I wanted to do this and I have found, in my opinion, a slightly improved solution of the throw answers. Just temporary supress the error messages and reactivate them later using setTimeout :

setTimeout(function() {
    window.onerror = function(message, url, lineNumber) {  
        return false;
    };
}, 50); // sets a slight delay and then restores normal error reporting
window.onerror = function(message, url, lineNumber) {  
    return true;
};
throw new Error('controlledError');
Cosmin
  • 1,482
  • 12
  • 26
2

The process is tedious, but in Firefox:

  1. Open a blank tab/window to create a new environment for the script from the current page
  2. Populate that new environment with the script to execute
  3. Activate the script in the new environment
  4. Close (that is, kill) that new environment to ...

stop or terminate JavaScript this [in a] way to [that it] prevent[s] any further JavaScript-based execution from occuring, without reloading the browser

Notes:

  • Step 4 only stops execution of JavaScript in that environment and not the scripts of any other windows
  • The original page is not reloaded but a new tab/window is loaded with the script
  • When a tab/window is closed, everything in that environment is gone: all remnants, partial results, code, etc.
  • Results must migrate back to the parent or another window for preservation
  • To rerun the code, the above steps must be repeated

Other browsers have and use different conventions.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
looped
  • 129
  • 1
  • 3
2

Define a variable inside the JavaScript function, set this variable to 1 if you want ot execute the function and set it to 0 if you want to stop it

var execute;
function do_something()
{
if (execute == 1)
{
// execute your function
}
else
{
 // do nothing
}
}
abubaha
  • 37
  • 1