-2

I'm newbie with javascript and I'm not able to figure out how to stop and wait until return key has been pressed.

Any help is appreciated.

Thanks in advance.

JPrado
  • 21
  • 1
  • 4

1 Answers1

2

You could either do it with a callback function, or using async await to wait a specific key is pressed:

const keyIsPressed = target => new Promise(resolve => {
  document.body.addEventListener('keyup', ({ key }) => {
    if(key.toUpperCase() === target.toUpperCase()) {
      resolve();
    }
  }, { once: true });
});

async function start() {
  console.log('Waiting for user to press enter...');
  
  // pause here until enter is pressed
  await keyIsPressed('enter');
  
  console.log('Enter is pressed.');
}

start();
Hao Wu
  • 17,573
  • 6
  • 28
  • 60