This question already has an answer here:
I'm developing a javascript class (with jQuery) to create custom popup, but I can not figure out how to "pause" the script to wait for user response (click on the OK button or cancel)
the class is like this:
function Popup()
{
}
Popup.Show = function(text)
{
var _response;
/* code to draw the popup elements*/
$("#button-ok").on("click",function()
{
_response = "ok!"
}
return _response
}
if, for example, use it in an alert, the method always return "undefined", because it does not wait for user click
alert(Popup.Show("hello"))
//return undefined before the popup appears
I tried to use a while loop like this:
Popup.Show = function(text)
{
var _response;
var _wait = true;
/* code to draw the window */
$("#button-ok").on("click",function()
{
_wait = false;
_response = "ok!"
}
while(_wait){};
return _response
}
but does not work (as I expected)
Then, how do I wait for the user click?
Thanks to all
JavaScript is asynchronous, you cannot "pauses" execution. Moreover, while javascript is running the entire user interface freezes, so the user cannot click the button.
Once you have registered the callback to the click event, the program continues its execution. The following lines in your script
will never get executed until the
Popup.Show
function returns. Perhaps this Nettuts article about javascript event programming will help you understand the paradigm.Here is a try to fix your code :
This is a typical JavaScript issue.
Now let's see what happens here. You're setting an onClick listener to the button, and assign a callback function for that event. Think of that function as of an argument you pass to another function. It is not executed directly.
Now instead of using something like
while(_wait){};
and force it to execute synchronous, you should work with that callback.This is a nice start into callbacks: http://javascriptissexy.com/
The context of what you are trying to do and why is a little vauge since it seems like you are trying to rebuild the 'alert' function. But 'alert' is a window function that is set up by the browser. This question seems like a duplicate of Stop page execution like the alert() function
Which basically talks about callback chaining, essentially encapsulating functionality so you can enforce the order in which they run. I also think you have a fundamental misunderstanding of how the code is run. As discussed event handlers are asynchronous and while the code is read in order, it is not going to run the function set within the event hanlders callback until that event has been triggered.