簡體   English   中英

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

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

我想知道如何在 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>

您可以在設置間隔后立即將超時設置為清除:

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)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM