function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } $('#target').click(function(e) { e.preventDefault(); // try to stop the countdown }); async function start() { for (index = 0; index < 5; index++) { await sleep(1000); $('#timer').text(index); } } start(); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div style="width: 100px; height:100px; background-color: red" id="target"></div> <div id="timer"></div> </body> </html>¿Hay alguna forma de borrar u omitir esta función de suspensión para que la cuenta regresiva se detenga cuando hago clic en un elemento específico (en este caso, el cuadrado rojo)?
En este caso, no necesita cancelar el tiempo de espera, simplemente ignórelo cuando se dispare.
Tenga una variable global (puede ser un espacio de nombres, por supuesto) que establezca en verdadero/falso cuando comience y falso/verdadero cuando desee detenerse.
Fragmento actualizado usando verdadero (activo) / falso (detenido).
También podría usar el opuesto var cancelled = false; luego configúrelo en verdadero cuando haga clic y compruebe si es falso.
var active; function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } $('#target').click(function(e) { e.preventDefault(); // try to stop the countdown active = false; }); async function start() { active = true; for (index = 0; index < 5; index++) { await sleep(1000); if (!active) break; $('#timer').text(index); } } start(); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="width: 100px; height:100px; background-color: red" id="target"></div> <div id="timer"></div>