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')
});