0

I want to write a JavaScript function like prompt() or confirm() where line execution wait until the mentioned function returned anything.

Say, I have a function abc() which will open a popup and then return a value. I want to hold the execution where the function was called.

function abc(){
    //----------
    return '';
}

function abc_caller(){
    var x = abc();
    alert(x);
}

Can anyone please help me regarding this?

Axel
  • 3,331
  • 11
  • 35
  • 58
  • *Possible duplicate:* http://stackoverflow.com/a/1729684/1563422 – Danny Beckett Mar 13 '13 at 07:36
  • Make your function do something that keeps the control and doesn't return it back – Hanky Panky Mar 13 '13 at 07:36
  • @DannyBeckett Not really. I think the OP actually wants to write a synchronous function that **blocks**. – Alvin Wong Mar 13 '13 at 07:37
  • 2
    That's not how you design API asking for user input in JavaScript : the user thread must release control which means no function can be blocking. Any decent API will require a callback that will be called upon user action. – Denys Séguret Mar 13 '13 at 07:39
  • 1
    This question is based on a bad understanding on how a JavaScript program must be designed. You must understand event based programming before designing your API. – Denys Séguret Mar 13 '13 at 07:42

3 Answers3

0

Your code should be -

function abc_caller(){
       var x = abc();
       var r=confirm("Your value is " + x);
       if (r==true)
       {
          alert("You pressed OK!")
       }
       else
       {
          alert("You pressed Cancel!")
      }
    }

More examples in http://www.w3schools.com/jsref/met_win_confirm.asp.

Hope this help you.

Piyas De
  • 1,786
  • 15
  • 27
0

This is not something browser builders want you to do. If a piece of Javascript is not responding within a certain amount of time the browser will start to think something is wrong and will ask the user if he wants to stop javascript from running.

You should create a callback function instead.

Lodewijk Bogaards
  • 19,777
  • 3
  • 28
  • 52
0

You clould use callback for this:
your function

function abc(callback){
    // whatever code here
    var result = ""; // or whatever processing result would be

    if (callback)
    {
        callback(result);
    }
}

usage:

abc(function(result){
    alert(result);
});

Edit: I think it's something similar to what @mrhobo was proposing

Ramunas
  • 3,853
  • 1
  • 30
  • 31