如何跳过/清除这个 sleep() 函数?

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>

有什么方法可以清除或跳过这个睡眠功能,以便在我单击特定元素(在本例中为红色方块)时停止倒计时?

在这种情况下你不需要取消超时,当它触发时忽略它就可以了

具有全局(当然可以是命名空间)变量,您在开始时将其设置为 true/false,在您想要停止时将其设置为 false/true。

使用 true(活动)/false(停止)更新了代码段。

您也可以使用相反的 var cancelled = false; 然后在单击并检查是否为 false 时将其设置为 true。

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>