0

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

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.