开发者

"break" javascript execution

开发者 https://www.devze.com 2023-01-21 17:33 出处:网络
I was wondering if there was a way to break javascript execution, something like this <script> if(already_done)

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 th开发者_如何转开发at 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.


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.


Put your code in a closure, like this:

(function (){

  if(already_done){
    return;
  }

  doSomeStuff();
})();

It should work.


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";
}


What would 'already_done' be? a boolean? it sounds to me like a loop... can you use something like?:

While ( !already_done ) { doSomeStuff(); }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号