Reputation: 105258
I was wondering if there was a way to break javascript execution, something like this
<script>
if(already_done)
{
return; //prevent execution (this yields an error)
}
doSomeStuff();
</script>
I know that this is possible like this:
<script>
if(already_done)
{
// do nothing
}
else
{
doSomeStuff();
}
</script>
But it's not the solution I'm looking for.
Hopefully this makes sense.
Upvotes: 2
Views: 4385
Reputation: 186762
Wrap it in a function which immediately executes.
(function() {
if (already_done) { return; }
doSomeStuff();
})();
FYI: return
is useless without being in a function context.
Also, this isn't a closure since it doesn't return an inner function which uses variables defined in an outer function.
Upvotes: 7
Reputation: 36637
You could use break
with a label:
<script>
testcase:
if (already_done) {
break testcase; //prevent execution
}
doSomeStuff();
</script>
though, as stated in other answers, wrapping it in a function is your best method.
Upvotes: 0
Reputation: 147
What would 'already_done' be? a boolean? it sounds to me like a loop... can you use something like?:
While ( !already_done ) { doSomeStuff(); }
Upvotes: 0
Reputation: 630627
You have one option directly in a <script>
block: you can throw an error, but this usually isn't desirable in the middle of a block of code...
if(already_done){
throw "Uh oh";
}
Upvotes: 3
Reputation: 2420
Put your code in a closure, like this:
(function (){
if(already_done){
return;
}
doSomeStuff();
})();
It should work.
Upvotes: 3