如何在 javascript 中使用 setInterval 和 clearInterval 在十秒后停止计时器

How to stop timer after ten seconds in javascript using setInterval and clearInterval?

本文关键字:十秒 计时器 clearInterval javascript setInterval      更新时间:2023-09-26

我想知道如何使用setInterval和clearInterval在javascript中十秒后停止计时器?这是我的代码示例,你能告诉我哪里出错了吗:

<!DOCTYPE html>
<html>
<head>
<script>
var tt=setInterval(function(){startTime()},1000);

function startTime()
{
  var today = new Date();
  var h=today.getHours();
  var m=today.getMinutes();
  var s=today.getSeconds();
  // add a zero in front of numbers<10
  m=checkTime(m);
  s=checkTime(s);
  today=checkTime(today);
  document.getElementById('txt').innerHTML=s;
}
function checkTime(tt)
{
if (tt==10)
  {
    tt="0" + tt;
    console.log(tt);
    clearInterval(tt);
  }
return tt;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
您可以在

设置间隔后立即将超时设置为清除:

var tt = setInterval(function(){ startTime() }, 1000);
setTimeout(function() { clearInterval(tt); }, 10000);

由于startTime()每秒运行一次,因此在其内部创建一个计数器以递增到 10,然后清除间隔。

var tt=setInterval(function(){startTime()},1000);
var counter = 1;
function startTime()
{
  if(counter == 10) {
    clearInterval(tt);
  } else {
    counter++;
  }
  document.getElementById('txt').innerHTML= counter;  
}

JSFiddle

因为你命名了一个名为 tt 的局部变量,它不允许你访问全局变量 tt。对变量名称的规划非常糟糕。

您的代码也不会在 10 秒

时停止,它会在时间在 10 秒或 10 分钟时停止。

function checkTime(xtt)
{
if (xtt==10)
  {
    xtt="0" + xtt;
    console.log(xtt);
    clearInterval(tt);
  }
return xtt;
}
这对

我有用。

var tt = setInterval(function(){ startTime() }, 1000);
setTimeout(function() { clearInterval(tt); }, 10000);

你可以这样做

setInterval(startTime, 1000).pipe(takeUntil(timer(10000)));