How to Stop JavaScript Execution

Is it possible to stop JavaScript execution?

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

How to terminate the script in 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 '';
}

How to stop a function during its execution - JavaScript

Stopping a running function is a bit different than what you are actually showing for code, which is an asynchronous operation happening outside of the function that initiated it.

Running functions can only be terminated from within the function and that is done with either a return statement or by throwing an exception.

return can be called conditionally so that the function doesn't always exit at the same point. This is often the case with form validation functions - - if something is determined to be invalid, a return is encountered so that the form is not submitted. If everything is valid, the return is skipped and the form is submitted.

Here's a simple example with return:

function foo1(){
console.log("Foo started...");
if(prompt("Type 1 to terminate right now or anything else to continue...") == "1"){
return; // Function will terminate here if this is encountered
}
console.log("Foo ending..."); // This will only be run if something other than 1 was entered
}

foo1();

How to terminate script execution when debugging in Google Chrome?

In Chrome, there is "Task Manager", accessible via Shift+ESC or through

Menu → More Tools → Task Manager

You can select your page task and end it by pressing "End Process" button.

How to stop scripts execution on the page?

You can enable/disable JavaScript on the page at any point using the command menu in DevTools. You can access this menu by using Cmd+Shift+P (Mac) or Ctrl+Shift+P (Windows/Linux).

Start typing Disable JavaScript and hit Enter to disable script execution.

In the following example, I ran an asynchronous timer to log an incremental count every 500ms. Upon disabling JavaScript, the execution was paused and nothing else logged to the console.

Disable

I later re-enabled JavaScript by typing 'Enable JavaScript` and hitting Enter. Upon doing this, the execution continued and the timer continued where it left off.

Paused

Note: Any synchronous code still running when you try to disable JavaScript won't be killed. It will finish and then further execution will be disabled.

How to stop the execution of below javascript code when taking prompt

You need to keep that append in the div inside the setTimeout() function and you can also check for input value is null or not for user input. Besides this, use setInterval() to keep showing the prompt as in your updated question so that when the user press cancel the prompt is closed forever.

$("div").append("I Want to Display this before user enter input in Prompt <br>")var promptLoop = setInterval(function(){  var input = prompt("test");  if(input !== null && input.trim() !== ''){    $("div").append("<br/>I Want to Display this after user enter input in Prompt. User input is " + input)  } else {    clearInterval(promptLoop);  }}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div></div>


Related Topics



Leave a reply



Submit