Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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) ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading