Reputation: 4216
I need to terminate the javascript from a function so that it doesn't execute the next block of codes and other functions called by the script, which follows the current function.
I found this existing question in SO : How to terminate the script in Javascript , where the solution is given as to trigger an error / exception which will terminate the script immediately.
But my case is different because, My purpose of terminating the script is to prevent an error which will come from the next functions, if the current function doesn't stop execution of the script. So, triggering another error to prevent an error is no way solving my purpose!
So, is there any other way of terminating the javascript instead of throwing an error / exception?
Please read my question properly before marking as duplicate, I have already explained why it doesn't solve my problem with the question I referred!.
Upvotes: 6
Views: 2384
Reputation: 1
Try using jQuery.Callbacks()
with parameter "stopOnFalse"
; jQuery.when()
, jQuery .then()
var callbacks = $.Callbacks("stopOnFalse");
function a(msg) {
var msg = msg || "a";
console.log(msg);
return msg
}
// stop callbacks here
function b() {
var msg = false;
console.log(msg)
return msg
}
// `c` should not be called
function c() {
var msg = new Error("def");
console.log(msg)
return msg
}
callbacks.add(a,b,c);
$.when(callbacks.fire())
.then(function(cb) {
// `c` : `Error`
if (cb.has(c)) {
console.log("callbacks has `c`"
, cb.has(c));
// remove `c`
cb.remove(c);
console.log(cb.has(c));
// empty `callbacks`
cb.empty();
// do other stuff
cb.add(a);
cb.fire("complete")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
Upvotes: 0
Reputation: 116448
Since you're inside a function, just return
.
Reading into your question a little more that it doesn't execute "other functions called by the script", you should return a boolean. For example, return false if you don't want the rest called, then wrap the remaining statements in an if:
function Foo() {
if (weAreInLotsOfTrouble) {
return false;
}
return true;
}
DoSomething();
DoSomethingElse();
if (Foo()) {
DoSomethingDangerous();
}
Upvotes: 5