代码示例:(标识:jsck_win_settimeout_cleartimeout_2)
<!DOCTYPE html>
<html>
<body>

<h1>Window 对象</h1>

<h2>setTimeout() 和 clearTimeout() 方法</h2>

<button onclick="startCount()">开始计时!</button>
<input type="text" id="demo">
<button onclick="stopCount()">停止计时!</button>

<p>点击“开始计时!”可启动定时器。输入字段将始终计数,从 0 开始。</p>

<p>点击“停止计时!”可停止计数。点击“开始计时!”可再次启动定时器。</p>

<script>
let counter = 0;
let timeout;
let timer_on = 0;

function timedCount() {
  document.getElementById("demo").value = counter;
  counter++;
  timeout = setTimeout(timedCount, 1000);
}

function startCount() {
  if (!timer_on) {
    timer_on = 1;
    timedCount();
  }
}

function stopCount() {
  clearTimeout(timeout);
  timer_on = 0;
}
</script>

</body>
</html>
运行结果: