Pablo Fernandez
Pablo Fernandez

Reputation: 105258

"break" javascript execution

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

Answers (5)

meder omuraliev
meder omuraliev

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

jrn.ak
jrn.ak

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

Josmas
Josmas

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

Nick Craver
Nick Craver

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

szanata
szanata

Reputation: 2420

Put your code in a closure, like this:

(function (){

  if(already_done){
    return;
  }

  doSomeStuff();
})();

It should work.

Upvotes: 3

Related Questions