1

I expect this has been asked before but I have searched and cannot find the correct answer.

If a function is called, and while doing that function another is used to check something, how can the initial function be halted from the second function?

a(1);
function a(v){
    check(v);
    alert "value correct";
    // continue

}

function check(v){
    if ( v!=1 ){
        alert "stop here number wrong";
        return;
    }
}

3 Answers 3

2

You have two options: pass up a return value or just return when you need to.

Demo Using a Passed-Up Return Value

a(1);
function a(v){
    var stopped = false;
    if (v==1){
      stopped = stop();
    }
    if (stopped) {
        return;
    }
    alert("did not stop");
}

function stop(){
    alert("I want it to stop here");
    return true;
}

Demo With a Simple Return

Even simpler: just return when you call stop():

a(1);
function a(v){
    if (v==1){
        stop();
        return;
    }
    alert("did not stop");
}

function stop(){
    alert("I want it to stop here");
}

P.S. You can't do alert "foo"; -- you need parentheses, like alert("foo");.

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

4 Comments

I've looked at your edits, but I'm not sure why my answer wouldn't work for you. Can you explain why it doesn't? Or, if it does, please remember to select an answer! :)
Hi, your code is good, but not what I'm looking for sorry, I'm trying to remove the IF from the initial function and only have it in the stop() function as I put in my second edit, as I will have several to check of different values, thanks again tho
@nathan Ah. Well, that's not possible. You can only return from one function at a time. You have to set some sort of return value or other state to check what happened in the stop() function. Anyway, glad I could help.
Thanks ED, that's as I though.
1

Do something like this:

a(1);
function a(v){
   if (v == 1){ // don't do anything }
   else { /** DO SOMETHING **/ }

}

Comments

1

Have the function return when you want it to stop running

See comments in code below for changes:

a(1);

function a(v) {

  if (v == 1) {
    // You may not even need this function
    // Just place a return 0; instead
    stop();

    // Have the parent function stop executing
    // As well as the child function
    return 0;
  }

  // Make sure to use parenthesis ()
  // When using "alert" function
  alert("did not stop");
}

function stop() {
  alert("I want it to stop here");
  return 0;
}

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.