Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
How to skip/ clear this sleep() function?

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>

Is there any way to clear or to skip this sleep function so that the countdown stops when I click a specific element(in this case, the red square) ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In this case you don't need to cancel the timeout, just ignore it when it fires

Have global (can be namespace'd of course) variable that you set to true/false when you start and false/true when you want to stop.

Updated snippet using true(active) / false(stopped).

You could also use the opposite var cancelled = false; then set it to true when you click and check for false.

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda