How to Terminate the Script in JavaScript

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

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

JavaScript stop script if a condition is not met

I think the main problem is that you're trying to use the conditional operator as a sloppy alternative to an if statement.

Just use an if statement, with return:

var lang   = script.getAttribute('lang');
if (!lang) {
return;
}

How to stop execution of a node.js script?

Using a return is the correct way to stop a function executing. You are correct in that process.exit() would kill the whole node process, rather than just stopping that individual function. Even if you are using a callback function, you'd want to return it to stop the function execution.

ASIDE: The standard callback is a function where the first argument is an error, or null if there was no error, so if you were using a callback the above would look like:

var thisIsTrue = false;

exports.test = function(request, response, cb){

if (thisIsTrue) {
response.send('All is good!');
cb(null, response)
} else {
response.send('ERROR! ERROR!');
return cb("THIS ISN'T TRUE!");
}

console.log('I do not want this to happen. If there is an error.');

}

Photoshop - Stop a script from a nested function

You may have figured it out by now, but I will answer for anyone else who may come across this.

When you return, it simply stops/exits current function, not the entire script. So for the script to stop, you need to return from the main script function, not from a nested function (in your case CheckFunction()), or even the button click function.

You may need to adjust your logic a bit here. Basically, your Function2 and Function3 should only run if CheckFunction passes. That means, that the only purpose of clicking the button is to check something. If check OK, you can run Function2 and Function3. If check not OK, stop script.

For your code, I would suggesting returning something from CheckFunction, then returning something again from your button click and using the button click function return value to check if further functions should run.

Something like this:

...

var continue = true; //control variable

button1.onClick = function() {
var check = CheckFunction();

if (!check) { //if false
continue = false;
}
}

if (continue) {

// here goes the other functions
Function2();
Function3();
}

//check function
function CheckFunction() {
if (condition is not met) {
alert ("Condition not met");
return false;
}
}

...

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

Early exit from function?

You can just use return.

function myfunction() {
if(a == 'stop')
return;
}

This will send a return value of undefined to whatever called the function.

var x = myfunction();

console.log( x ); // console shows undefined

Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.

return false;
return true;
return "some string";
return 12345;


Related Topics



Leave a reply



Submit