Reputation: 1489
I have function that waits for a certain user response (pressing a key).
async function alert(){
let alert_response = await testing_501_alert_response()
}
async function testing_501_alert_response() {
key_code = [99, 67, 113, 81, 114, 82]
return new Promise((resolve) => {
document.addEventListener('keydown', onKeyHandler);
function onKeyHandler(e) {
if (key_code.includes(e.keyCode)) {
document.removeEventListener('keydown', onKeyHandler);
resolve(e.keyCode);
}
}
});
}
I would like to be able to abort this "wait" i.e. have a button on the form with onlclick event that will terminate the execution.
Upvotes: 0
Views: 78
Reputation: 1720
Here is an example of implementing a removeEventListener on button click:
function trigger() {
key_code = [99, 67, 113, 81, 114, 82] // c
document.addEventListener('keydown', onKeyHandler);
}
function cancel() {
document.removeEventListener('keydown', onKeyHandler);
}
function onKeyHandler(e) {
console.log(e.keyCode)
if (key_code.includes(e.keyCode)) {
document.removeEventListener('keydown', onKeyHandler);
// do whatever you want with this handler here
}
}
body { margin: 0; }
.as-console-wrapper { min-height: 85%; top: auto; }
<button onclick="trigger()">trigger</button>
<button onclick="cancel()">cancel</button>
https://jsfiddle.net/9b2xf1no/2/
Upvotes: 2