Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
javascript termina onkeydown eventlistener

Tengo una función que espera una determinada respuesta del usuario (presionando una tecla).

 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); } } }); }

Me gustaría poder abortar esta "espera", es decir, tener un botón en el formulario con el evento onlclick que terminará la ejecución.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Aquí hay un ejemplo de implementación de removeEventListener al hacer clic en el botón:

 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/

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!