386

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.

7
  • 11
    return - inside a function Commented Feb 15, 2012 at 18:11
  • 1
    Dup of stackoverflow.com/questions/550574/… ? Commented Aug 10, 2015 at 0: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. Commented Dec 28, 2017 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? Commented Jun 15, 2021 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? Commented Oct 19, 2022 at 14:45

11 Answers 11

663
+250

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

Sign up to request clarification or add additional context in comments.

13 Comments

Note: All remaining asynchronous functions like setTimeout or XMLHttpRequest will still execute. Currently there is no standard way to completely terminate JavaScript.
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.
@gattsbr Doesn't that still cause the next lines to be immediately executed?
+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.
@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.
|
153

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

thisFunctionDoesNotExistAndWasCreatedWithTheOnlyPurposeOfStopJavascriptExecutionOfAllTypesIncludingCatchAndAnyArbitraryWeirdScenario();

Or something like:

new new

10 Comments

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.
From now on, i will include this function in everything that i write, let the meme be created!
Just make sure to explain this line in your code. If someone after you see this line, he will be confused as hell :)
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.
Now that is thinking outside the box. Syntax errors on purpose!
|
43

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/

7 Comments

Is that part of the ECMA standard or a browser extension?
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.
I mean the Error object.
This can tell you more than I know about it: developer.mozilla.org/en-US/docs/JavaScript/Reference/…
|
32

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.

4 Comments

FYI, chrome dev tools allows you to toggle ":hover" on elements for such scenarios
":hover" is css thing, if you show tooltip with mouseover() for example, this doesn't help
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).
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.
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.

4 Comments

How can we prevent that?
I made a test for timeouts before I read your post. It confirms that an exception will not terminate a timout. jsfiddle.net/skibulk/wdxrtvus
You might consider this to clear timeouts and intervals: stackoverflow.com/a/8860203/6465140
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".
25

I am using

return false;

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

3 Comments

You don't need false... just return;
Doesn't stops if it was an ajax call.I mean you have a function that executes after ajax fetches data.return or return false only exits from that function and not the method you intend to stop if ajax fails.
@EddieB you are a genius
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.

Comments

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.

Comments

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

1 Comment

Supressing errors is an excellent idea.
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
}
}

1 Comment

This does not work in every case but it did work for me in my situation, thanks!
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.