9

What is the equivalent of PHP's exit; in Javascript/jQuery?

I need to stop my script early depending on certain conditions... The only answers I could find from search was stopping forms from submitting...

2
  • possible duplicate of How to terminate the script in Javascript Commented Sep 4, 2012 at 10:47
  • In PHP, exit() can be called anywhere. In JavaScript, return can only be called in a function, not in file scope. Commented Nov 24, 2018 at 16:16

4 Answers 4

15

You could try:

throw "stop execution";

Using return you will skip the current function, that's why throwing is more similar to PHP exit();

Sign up to request clarification or add additional context in comments.

1 Comment

When I tried this I got an "uncaught exception" error. In PHP, I believe, exit() stops without error.
3

I would finish a function early with a return statement:

return;

1 Comment

Only skipped the function and some of the script still ran for me.
2

A javascript function is terminated by calling return. Usually you will be in the context of a function or something. Also event handlers (like for onclick on an element) will behave like a function and accept return.

Comments

1

From looking on your certain problem, and for everyone else. Please see this. This MIGHT help you.

Just put this one line

if(exit_condition!=true)

and also this requires your codes to be inside of

$(document).ready()

if(exit_condition!=true)
    $(document).ready(function() {
      // Your code
      // Your code
      // Your code
      // Your code
    });

I have also encountered this issue, @Jamesking56 has encountered. And this is my solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.