Skip to content

Instantly share code, notes, and snippets.

@trustedtomato
Last active August 25, 2017 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trustedtomato/02060a3c6e160463fdfe86ecab4b45b9 to your computer and use it in GitHub Desktop.
Save trustedtomato/02060a3c6e160463fdfe86ecab4b45b9 to your computer and use it in GitHub Desktop.
Wait for a key in JS
/** Wait for the given key; if key is omitted, any key will trigger. It resolves the event. */
function waitForKey(key){
return new Promise(resolve => {
var onkeydown = e => {
if(typeof key === 'undefined' || e.key === key){
document.removeEventListener('keydown', onkeydown);
resolve(e);
}
};
document.addEventListener('keydown', onkeydown);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment