如何使用 setInterval 和 clearInterval 在 javascript 中十秒后停止计时器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18719339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to stop timer after ten seconds in javascript using setInterval and clearInterval?
提问by Formula 1
I was wondering how can I stop a timer after ten seconds in javascript using setInterval and clearInterval?? Here's my code example, could you please tell me where I'm going wrong:
我想知道如何在 javascript 中使用 setInterval 和 clearInterval 在十秒后停止计时器?这是我的代码示例,你能告诉我哪里出错了:
<!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>
回答by Tomzan
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);
回答by Tricky12
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;
}
回答by epascarello
Because you named a local variable named tt which does not let you access the global variable tt. Very bad planning on variable names.
因为您命名了一个名为 tt 的局部变量,它不允许您访问全局变量 tt。对变量名称的规划非常糟糕。
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;
}
回答by Sayid Dastaan
This works for me.
这对我有用。
var tt = setInterval(function(){ startTime() }, 1000);
setTimeout(function() { clearInterval(tt); }, 10000);
回答by itai schwed
you can do that
你可以这样做
setInterval(startTime, 1000).pipe(takeUntil(timer(10000)));