0

I'm looking to create an interface that simulates an interactive javascript console, where users can print get input directly on the page itself. The problem is with the input - when the user asks for input, the JS needs to pause execution until the "Enter" button is clicked so that the input can be collected and sent on to continue.

The purpose is to teach very basic javascript like one would teach, say, Python, where the input() function blocks further execution. I know this is achievable with callbacks in JS but I'm trying to make this as beginner-friendly as possible.

Is this something that's possible with Javascript? I also know that prompt() would work here but I want to see if there's a more visually appealing way to do it.

Here's the code I have, in case it gives a better idea of what I'm trying to do:

let $go;
const $input = document.querySelector('input');
const $button = document.querySelector('button');
const $output = document.querySelector('code');

function block() {
  if (!$go) {
    console.log('continuing blocking');
    setTimeout(block, 1000);
  }
}

function output(msg) {
  $output.innerHTML += msg;
}

function input(msg) {
  console.log('waiting for input');
  $input.placeholder = msg;
  $go = false;

  block();

  console.log('returning');
  return $input.value;
}

$button.addEventListener('click', function(){
  $go = true;

  console.log('clicked')
});
tic
  • 137
  • 12
  • Would https://stackoverflow.com/questions/16934667/what-methods-are-blocking-in-javascript help? – evolutionxbox Nov 28 '17 at 16:55
  • It does help, not sure why that didn't come up in my search. Guess the answer is pretty simple then. :( Thanks! – tic Nov 28 '17 at 17:00
  • No problem! - I'm sorry that you didn't get the answer you wanted. – evolutionxbox Nov 28 '17 at 17:20
  • Why do you need it to block? What are you trying to block? – Dave Newton Nov 28 '17 at 20:08
  • @DaveNewton I want to be able to ask the user for input synchronously, through an HTML interface, but this doesn't seem to be possible. – tic Nov 29 '17 at 17:21
  • I'm trying to understand what you mean by "synchronously". What behavior are you trying to inhibit? – Dave Newton Nov 29 '17 at 19:01
  • @DaveNewton sorry about the late replies - I keep forgetting to refresh the page (SE reminds me via emails the next day). I'm looking to be implement a line of code that acts as a "wait until this event happens" or "wait until this flag is true", without using callbacks for the code that needs to be delayed. Let me know if I'm not making sense. – tic Nov 30 '17 at 19:56

0 Answers0