Home > Back-end >  How to skip/ clear this sleep() function?
How to skip/ clear this sleep() function?

Time:11-16

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related