javascriptasync-awaitpromise

Why does the ENTER key release the wait?


The button executes the "resolve" function and releases the wait, as expected.
But then the ENTER key releases the wait also. What's going on?

<html>
  <head>
    <title> Q:await </title>
    <meta charset="utf-8">
    <script>
  "use strict";
  let fnresolve, n=0; // globals
window.onload = function() {
  zlog('Hit the button, then the ENTER key');
  zlog();
  Main();
}
async function Main() {
  do {
    zlog('before wait', ++n);    
    let pMain = new Promise((res) => { fnresolve = res; } ); // save the res function
    await pMain;
    zlog('after wait', n); zlog('');    
  } while (1);
}
function zlog() {
  document.getElementById('zlog').innerHTML += (Object.values(arguments).join(', ')) + '<br />';
}
    </script>
  </head>
  <body>
  <button onclick='fnresolve();'> fnresolve </button>
  <div id='zlog'></div>  
  </body>
</html>

EDIT: The answer and comments inspired the fix:

<button onclick='fnresolve();this.blur();'> fnresolve </button>

Solution

  • <button> element. In a typical HTML document, pressing the "ENTER" key can trigger the first button on the page as if it were clicked. Since your fnresolve function is associated with the button's onclick event, pressing "ENTER" triggers this event, causing the promise to be resolved.

    Here is what you should update

    <button type="button" onclick='fnresolve();'> fnresolve </button>