Reputation: 323
I have a sort of a strange problem with the structure of my JS code. It is a convertor from Brainfuck to JavaScript. Then it runs the code it has generated.
With this in mind, I have noticed a problem with the prompt();
command. It seems to, in some situations, show the prompt box before the previous command (changing the DOM) finishes.
My solution is to show an <input type="text">
box, initially set to display:none
in CSS. However, I need a way to wait for the input to change. I tried this code:
while (document.getElementById("input") == ""){}
But this freezes the DOM. I need a way to passively wait for any user input, then continue with the script.
Keep in mind, I can't use onkeydown, external functions, etc.
Thanks!
Upvotes: 1
Views: 94
Reputation: 351384
To wait for user input in a non-blocking way, you need to run asynchronous code. This you do by providing a callback function which should be called when a certain event takes place. In your case, this could be when the input value is submitted:
var inp = document.getElementById("inp");
inp.addEventListener('change', function(e) {
var value = this.value;
alert('you entered: ' + value);
// all code that needs the value, should come here,
// or should be called from here.
});
Exit field to submit value:
<input id="inp">
Upvotes: 1
Reputation: 53229
There's no way to stop script execution besides using native functions like alert
, confirm
, prompt
.
Try wrapping your prompt inside a setTimeout
. Start with a value of 0 to see if it works.
setTimeout(function () {
prompt('your prompt');
}, 0);
Using setTimeout
with a value of 0 pushes the execution of the prompt to the back of the event loop, and may possibly run after your DOM updates.
Read more about this technique here: https://www.quora.com/What-does-setTimeout-with-a-0ms-delay-do
Upvotes: 1