How can I make a program wait for a button press in javascript?
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.
Ok, probably you wanted this kind of thing, you can implement the events to flag the key from Pentium10's answer:
You can make a function called for example waitForIt() in which you set a setTimeout() function that calls the same method until a global variable is true (set by you press button action).
For example:
<html>
<head>
<script type="text/javascript">
var buttonpressed = false;
function waitForIt() {
if (!buttonpressed ) {
setTimeout(waitForIt,2500);
} else {
document.getElementById('info').value='ok';
}
}
function startSomething() {
document.getElementById('info').value='';
waitForIt();
document.getElementById('info').value='waiting';
}
function setButtonPressed() {
buttonpressed = true;
}
</script>
</head>
<body>
<br>
<input type='text' style="width: 200px;" id="info" />
<br>
<input type='button' style="width: 200px;" value="Start" onclick="javascript: startSomething();">
<br>
<br>
<input type='button' style="width: 200px;" value="Continue" onclick="javascript: setButtonPressed();">
</body>
</html>
You could call the waitForIt() method directly but i made it so you can view what is happening. Sorry for the mess in the example but i don't have much time to spare :)
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