Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a program wait for a button press in javascript?

I need to modify some legacy javascript code. There's a place where I want to wait until the user presses one of two buttons and then continue with the program flow (like prompt() function). How can this be achieved ?

like image 611
Eugene Yarmash Avatar asked Feb 08 '10 13:02

Eugene Yarmash


People also ask

Does JavaScript wait for response?

But in some case, Javascript behaves as asynchronous, such as in AJAX or Axios calls. It makes a call to the API but does not wait for the API to return result, and progresses with the next queued event.

How do you wait for a function to execute?

Use async/await to Wait for a Function to Finish Before Continuing Execution. Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait .


2 Answers

Simply create a promise and store the resolve function outside its scope in a global variable. Then let the program wait for the promise to resolve (using "async" and "await"). The promise is resolved on a button click by calling that global variable. I used this technique in a chess program to wait for the answer to a promotion popup window:

var _promote; /* resolve-function reference */

async function promote_piece(pce, fld, clr) {
  var type;
  (...)
  show_mpw(clr); /* show modal promotion window */
  var promise = new Promise((resolve) => { _promote = resolve });
  await promise.then((result) => { type = result });
  if (type === undefined) type = "Q";
  (...)
}

So after creating the promise, the program will wait until the popup window resolves it. The popup window resolves the promise as follows when it is closed:

_promote(type); /* resolve promotion-promise */

N.B. Please keep in mind that in this case the promote_piece() function itself also has to be called with the "await" keyword! Otherwise the program will execute it asynchronously and continue anyhow

like image 161
Jurjen van der Hoek Avatar answered Oct 20 '22 05:10

Jurjen van der Hoek


You need to break your function at that point, and add another function to catch the user's button press event.

You can use Narrative Javascript to introduce blocking behavior and simplify it (so you don't need to break up your function into two part), but note that this library has been abandoned since 2013.

like image 42
kennytm Avatar answered Oct 20 '22 04:10

kennytm