Is there a way to pause code execution in JS? I'm trying to create a browser based terminal, and I'm having trouble creating a user input type functionality.
Essentially I want to have a parameter called currentCommand which initializes in a false state and a function which waits for the currentCommand variable to change before completing like:
while(!currentCommand) {
pass;
}
Here's how I'd like it to be applied:
let currentCommand = false; // this variable holds the command the user has entered
// Placeholder of a user text input
document.addEventListener('keydown', () => {
currentCommand = 'Timmy';
}
// Problematic function
function getAnswer(){
currentCommand = false;
// something that will pause the function while currentCommand is false
return currentCommand
}
// Example of implementation
console.log('Hi what is your name?');
let answer = getAnswer();
console.log(`${asnwer}, that's a silly name`);
An example implementation for context: https://jsfiddle.net/u98r1dyp/17/#&togetherjs=jmnaRa89uT
1 Answer 1
The closest you can probably get would be to promisify whichever API you're using and await its resolution:
const getAnswer = () => new Promise((resolve) => {
document.addEventListener('keydown', () => {
resolve('Timmy');
});
});
(async () => {
console.log('Hi what is your name?');
const answer = await getAnswer();
console.log(`${answer}, that's a silly name`);
})();
(also note that you need another ) at the end of addEventListener, and you probably want to spell answer right - asnwer is never defined)