简体   繁体   English

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

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

I was wondering how can I stop a timer after ten seconds in javascript using setInterval and clearInterval??我想知道如何在 javascript 中使用 setInterval 和 clearInterval 在十秒后停止计时器? Here's my code example, could you please tell me where I'm going wrong:这是我的代码示例,你能告诉我哪里出错了:

<!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>

you can set timeout on clear like this right after you set the interval:您可以在设置间隔后立即将超时设置为清除:

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

Since startTime() will run every second, make a counter to increment to 10 inside of it, then clear the interval.由于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 JSFiddle

Because you named a local variable named tt which does not let you access the global variable tt.因为您命名了一个名为 tt 的局部变量,它不允许您访问全局变量 tt。 Very bad planning on variable names.对变量名称的规划非常糟糕。

Your code also will not stop at 10 seconds, it will stop when the time is at 10 seconds or 10 minutes.您的代码也不会在 10 秒时停止,它会在时间为 10 秒或 10 分钟时停止。

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

This works for me.这对我有用。

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

setTimeout(function() { clearInterval(tt); }, 10000);

你可以这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM