Let's say I have this code:
var myVar = 0;
function myFunctionOne() {
myVar = myVar + 2;
if(myVar <= 3) {
alert("all is good");
} else {
showError(myVar);
}
}
function myFunctionTwo() {
myVar = myVar + 2;
if(myVar <= 3) {
alert("all is good");
} else {
showError(myVar);
}
}
function myFunctionThree() {
//This should never run....
myVar = myVar + 2;
if(myVar <= 3) {
alert("all is good");
} else {
showError(myVar);
}
}
function showError(myVar) {
alert("Error Var is larger than 3. Var is" + myVar);
return false;
//This doesn't seem to stop anything
}
myFunctionOne();
myFunctionTwo();
myFunctionThree();
Here is also the fiddle: http://jsfiddle.net/dzjk44Lr/
What can I put inside my showError() function, that will kill any subsequent function calls? In this example, myFunctionThree(); should never run.
I know this is a simple example, but I'm trying to get my head around the module pattern, and in my module I have a lot of functions that delegate work, and modify variables. So if one function fails, or is given an illegal variable, I want everything to stop and show the user an error. Because if there was an error in myFunctionOne() for example, there is no point in continuing to execute any of the other code.
I guess, I'm looking for something like the php exit() function.
Any advice about how to do this, or how I should do it differently would be greatly appreciated.
You can throw an error:
throw new Error("Error Var is larger than 3. Var is" + myVar);
You can use javascript throw statement.
According to Mozilla MDN
Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
Example:
throw "An error ocurred."
You can also go pro and throw an error object like this:
throw new MyAppError("custom error str", 128);
Related
I have a function:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
Is there something like exit() in JavaScript?
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;
Apparently you can do this:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
I can't see any downsides yet. But it doesn't seem like a common use.
Derived this answer: JavaScript equivalent of PHP’s die
function myfunction() {
if(a == 'stop')
return false;
}
return false; is much better than just return;
This:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
Using a little different approach, you can use try catch, with throw statement.
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
if you are looking for a script to avoid submitting form when some errors found, this method should work
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
change the Submit Button type to "button"
<input value="Save" type="button" onClick="verifyData()">
hope this help.
Using a return will stop the function and return undefined, or the value that you specify with the return command.
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}
I think throw a new error is good approach to stop execution rather than just return or return false. For ex. I am validating a number of files that I only allow max five files for upload in separate function.
validateMaxNumber: function(length) {
if (5 >= length) {
// Continue execution
}
// Flash error message and stop execution
// Can't stop execution by return or return false statement;
let message = "No more than " + this.maxNumber + " File is allowed";
throw new Error(message);
}
But I am calling this function from main flow function as
handleFilesUpload() {
let files = document.getElementById("myFile").files;
this.validateMaxNumber(files.length);
}
In the above example I can't stop execution unless I throw new Error.Just return or return false only works if you are in main function of execution otherwise it doesn't work.
I dislike answering things that aren't a real solution...
...but when I encountered this same problem, I made below workaround:
function doThis() {
var err=0
if (cond1) { alert('ret1'); err=1; }
if (cond2) { alert('ret2'); err=1; }
if (cond3) { alert('ret3'); err=1; }
if (err < 1) {
// do the rest (or have it skipped)
}
}
Hope it can be useful for anyone.
If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.
function myfunction(e)
{
e.stopImmediatePropagation();
................
}
exit(); can be use to go for the next validation.
type any random command that throws an error, for example:
exit
or
die:-)
The "if statement" in my code keeps doing a console.log which comes after the "if statement" even though the code inside it is calling the search function.
Is there any way I can prevent this?
function search() {
/**
* The Tweet checking algorithm.
* #private
*/
function checkTweet(tweet) {
if (tweet.favorite_count <= 5) {
log('less than 5 likes');
search();
}
if (getBlockedWords().includes(tweet.text)) {
log('includes blocked words');
search();
}
console.log(tweet); // This line activates even though the if statements are calling the search function.
}
Twitter.get(
'search/tweets',
{q: getSearchKey(), count: 30, lang: 'en'},
function(err, data, response) {
let tweetList = [];
if (!err) {
for (let i = 0; i < data.statuses.length; i++) {
let tweet = data.statuses[i];
tweetList.push(tweet);
}
var result = tweetList[Math.floor(Math.random() * tweetList.length)];
checkTweet(result);
} else {
log(err);
sleep(search);
}
});
}
An if statement doesn't necessarily stop the flow of code. An if statement runs if the condition evaluates as true. Whether is continues running is dependent on the code within the if statement.
One simple way of accomplishing this is to simply use return within your if block. This will prevent the rest of the code within that function from running.
function checkTweet(tweet) {
if (tweet.favorite_count <= 5) {
log('less than 5 likes');
search();
return;
}
if (getBlockedWords().includes(tweet.text)) {
log('includes blocked words');
search();
return;
}
console.log(tweet); // This line activates even though the if statements are calling the search function.
}
if(a.value==1 && b.value==2)
{
try{callFunc() }catch(e) {}
}
frm.submit();
Inside function callFunc(), what do I have to write so that execution completely stops?
It should not execute frm.submit();
function callFunc()
{
//stop execution here -- ensure it won't execute fm.submit()
}
Better one is
function Abort()
{
throw new Error('This is not an error. This is just to abort javascript');
}
than from any where call this
try
{
for(var i=0;i<10;i++)
{
if(i==5)Abort();
}
} catch(e){}
For you
function callFunc()
{
//stop execution here
Abort();
}
//code from where you are going to call
try
{
if(a.value==1 && b.value==2)
{
callFunc()
}
frm.submit();
}
catch(e) {}
As you've discovered, aborting JavaScript almost always involves exceptions. If you truly can't change the wrapper, then you might have to resort to something a bit more extreme. One (evil) way to kill the script is to convince the browser that it's taking too long, by running an infinite loop:
function callFunc()
{
//stop execution here
var n = 1;
while (n) {
n += 1;
}
}
Modern browsers will let the user kill the script after a while. Granted, it will make your site seem broken, but that should give you the leverage you need to get a better API in place.
If the busy-loop is too extreme, you could replace the simple addition with a plugin-based sleep, or perhaps a synchronous network request that takes an extremely long time, wrapped in its own try/catch safety net.
I understand what you are trying to do. You don't want to kill the Javascript interpreter, you just want to prevent the form submission from proceeding.
HTML
<form id="myForm">
…
</form>
Javascript
// Setup…
var frm = document.getElementById('myForm'),
a = { value: 1 },
b = { value: 2 };
// Can change this code
var callFunc = function() {
// Throwing will do nothing here, since
// exceptions are being caught in a try/catch
// Instead, let's overwrite the submit handler with one that
// will cancel the form submission, then restore the old handler
var oldSubmitHandler = frm.submit;
var killHandler = function(e) {
// Prevents the submission
e.preventDefault();
// Restores the old handler
frm.submit = oldSubmitHandler;
};
frm.submit = killHandler;
};
// Can't change any of this code
if(a.value==1 && b.value==2)
{
try { callFunc() } catch(e) { }
}
// Want to stop this from happening
frm.submit();
See it in action: http://jsfiddle.net/3A7xC/
Better way is this:
if(a.value==1 && b.value==2)
{
try{
callFunc();
frm.submit();
}
catch(e) {
// stop execution
}
}
If an exception is thrown in function callFunc, the frm.submit(); line would not be executed. Instead, it will skip to the catch clause
Lots of answers, one more for fun.
You can put the code in a function, have the try block throw an error, then return from the catch clause:
function foo() {
var a = {value:1};
var b = {value:2};
if(a.value==1 && b.value==2) {
try {
callFunc();
} catch(e) {
alert(e.message);
return;
}
}
alert('error didn\'t stop me!');
}
function callFunc() {
throw new Error('This is an error.');
}
Otherwise you can set a flag in the catch block and test for it immediately afterward before going any further. Or take one of the other answer's options.
So the inside of the callFunc is the only thing you can change?
How about this:
callFunc(){
frm.submit(function() {
alert('this should not submit');
return false;
});
}
To kill the execution of a JS script use:
system.stop()
You can abort javascript execution using throw:
if(a.value==1 && b.value==2){
try{callFunc() }catch(e) {}
}
frm.submit();
function callFunc() {
throw "stop execution";
}
I can't find a recommended way to stop a function part way when a given condition is met. Should I use something like exit or break?
I am currently using this:
if ( x >= 10 ) { return; }
// other conditions;
Return is how you exit out of a function body. You are using the correct approach.
I suppose, depending on how your application is structured, you could also use throw. That would typically require that your calls to your function are wrapped in a try / catch block.
use return for this
if(i==1) {
return; //stop the execution of function
}
//keep on going
The return statement exits a function from anywhere within the function:
function something(x)
{
if (x >= 10)
// this leaves the function if x is at least 10.
return;
// this message displays only if x is less than 10.
alert ("x is less than 10!");
}
Use a try...catch statement in your main function and whenever you want to stop the function just use:
throw new Error("Stopping the function!");
throwing the exception when the condition is met to break the function.
function foo() {
try {
if (xyz = null) //condition
throw new Error("exiting the function foo");
} catch (e) {
// TODO: handle the exception here
}
}
Try using a return statement. It works best. It stops the function when the condition is met.
function anything() {
var get = document.getElementsByClassName("text ").value;
if (get == null) {
alert("Please put in your name");
}
return;
var random = Math.floor(Math.random() * 100) + 1;
console.log(random);
}
if (OK === guestList[3]) {
alert("Welcome");
script.stop;
}
I have a function:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
Is there something like exit() in JavaScript?
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;
Apparently you can do this:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
I can't see any downsides yet. But it doesn't seem like a common use.
Derived this answer: JavaScript equivalent of PHP’s die
function myfunction() {
if(a == 'stop')
return false;
}
return false; is much better than just return;
This:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
Using a little different approach, you can use try catch, with throw statement.
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
if you are looking for a script to avoid submitting form when some errors found, this method should work
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
change the Submit Button type to "button"
<input value="Save" type="button" onClick="verifyData()">
hope this help.
Using a return will stop the function and return undefined, or the value that you specify with the return command.
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}
I think throw a new error is good approach to stop execution rather than just return or return false. For ex. I am validating a number of files that I only allow max five files for upload in separate function.
validateMaxNumber: function(length) {
if (5 >= length) {
// Continue execution
}
// Flash error message and stop execution
// Can't stop execution by return or return false statement;
let message = "No more than " + this.maxNumber + " File is allowed";
throw new Error(message);
}
But I am calling this function from main flow function as
handleFilesUpload() {
let files = document.getElementById("myFile").files;
this.validateMaxNumber(files.length);
}
In the above example I can't stop execution unless I throw new Error.Just return or return false only works if you are in main function of execution otherwise it doesn't work.
I dislike answering things that aren't a real solution...
...but when I encountered this same problem, I made below workaround:
function doThis() {
var err=0
if (cond1) { alert('ret1'); err=1; }
if (cond2) { alert('ret2'); err=1; }
if (cond3) { alert('ret3'); err=1; }
if (err < 1) {
// do the rest (or have it skipped)
}
}
Hope it can be useful for anyone.
If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.
function myfunction(e)
{
e.stopImmediatePropagation();
................
}
exit(); can be use to go for the next validation.
type any random command that throws an error, for example:
exit
or
die:-)