I want method to prevent the code from the resumption of what he is doing if the condition is not true.
This is my code
function doSomething{
if(1==2){
alert("Can I access to your event?");
}else{
//1 not equals 2, so please die
// I tried die() event; It worked, But i get this error in the console
// Uncaught TypeError: Cannot call method 'die' of undefined
}
}
$(".foo").click(function(){
doSomething();
alert("welcome, 1 == 1 is true");
}
You could just return false within the click handler, I suppose. For example:
function doSomething () {
if(1==2){
alert("Can I access to your event?");
}else{
return false; // tell the click handler that this function barfed
}
}
$(".foo").click(function(){
if(doSomething() === false){ //check to see if this function had an error
return false; //prevent execution of code below this conditional
}
alert("welcome, 1 == 1 is true");
}
Judging from the code, you probably want to just throw an exception ;-)
function doSomething
{
if(1==2){
alert("Can I access to your event?");
}else{
throw 'blah';
}
}
This will unwind the stack immediately until the exception is caught or it reaches the global level.
Try this traditional way
function doSomething () {
if(1==2){
alert("Can I access to your event?");
return true;
}else{
return false
}
}
Usage:
$(".foo").click(function(){
if(doSomething()){
alert("welcome, 1 == 1 is true");
}else{
alert("Sorry, 1 == 1 is false");
}
}
You could throw an exception:
function doSomething (){
if (1 == 2) {
alert("Can I access to your event?");
} else {
throw "this is a fatal error";
}
}
$(".foo").click(function () {
doSomething();
alert("welcome, 1 == 1 is true");
});
FIDDLE
Of course you should handle that exception to not get errors in your log, maybe like so:
$(".foo").click(function () {
try {
doSomething();
alert("welcome, 1 == 1 is true");
} catch (err) {
// do nothing but allow to gracefully continue
}
});
FIDDLE
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:-)
I'd like to receive a response (true or false) from a called function to decide if the function should continue or stop. Look at the following code for better understanding:
function function1() {
function2(); // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
}
function function2() {
if (condition === value) {
// do something, give function1 a response to continue
} else {
// do something, give function1 a response to stop
}
}
Updated:
function function1() {
console.log('call function2');
function2(); // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
console.log('back from function2');
}
function function2() {
if (condition === false) {
console.log('condition === false');
return;
}
}
You don't need an else on the statement. check to see if your variable is false and if it is it will return if not the rest of your function will run automatically.
function function1() {
function2(); // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
}
function function2() {
if (condition === false) {
return;
}
}
If function2 is synchronous you can just return:
function function1() {
if(!function2()){
return
}; // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
}
function function2() {
if (condition === value) {
return true;
} else {
return false;
}
}
If function 2 does something asynchronous and expects a callback (one of the tags in your question) then it may be easier to write a function that will use function2 and returns a promise.
function function1(condition) {
console.log('calling function 2');
function2AsPromise(condition).then(function(
function2Result
) {
if (!function2Result) {
console.log('function 2 result is false');
return;
}
console.log('function 2 result is true');
});
console.log('exiting function 2');
}
function function2(condition, callback) {
setTimeout(function() {
if (condition) {
callback(true);
} else {
callback(false);
}
}, 2000);
}
function function2AsPromise(condition) {
return new Promise(function(resolve) {
function2(condition, resolve);
});
}
function1(false);
const function1 = check => {
if (check === false) {
return;
} else {
console.log("back from function2");
}
};
function1(false) // console.log doesn't run
function1(true) // console.log runs
make sure that you pass in a Boolean value.
I am trying to use CoffeeScript to setup an AJAX callback function like so:
The Pattern
function doAjax(callback)
{
$.ajax(url, data)
.done(function(){
// ... do stuff here ...
callback(true);
}).fail(function(){
callback(false);
});
}
function doSomething()
{
doAjax(function(result){
if (result == true )
console.log('success');
else
console.log('failed');
});
}
I am using the following CoffeeScript to do this (this is within an object):
CoffeeScript
doAjax: (callback) ->
$.getJSON(url)
.done( (data) ->
if something == true
callback(true)
else
callback(false)
).fail( () ->
callback(false)
)
doSomething: () ->
this.doAjax(function:(result)->
if result == true
console.log "true"
else
console.log "false"
It results in the following compiled JavaScript like this:
Compiled JS
MyObject.prototype.doAjax = function(callback) {
return $.getJSON(url).done(function(data) {
if (something == true) {
callback(true); // <--- The error happens here
} else {
callback(false);
}
}).fail(function() {
callback(false);
});
};
MyObject.prototype.doSomething = function() {
return this.doAjax({
"function": function(result) {
var message;
if (result === true) {
return console.log("true");
} else {
return console.log("false");
}
}
});
};
And I get the error (at the marked line above):
Uncaught TypeError: object is not a function
What am I doing wrong in my CoffeeScript here?
change this
this.doAjax(function:(result)->
to this
this.doAjax((result)->
functions in coffeescript are declared with () ->. function:() -> creates an object with a property called function that contains the actual function
Actually you are trying to callback function to perform some operation after successful ajax call, but you are calling the object as function.Define some function and use it to callback.thank you, for further assistance please report to me.
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 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:-)