5

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:

<!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>
Formula 1
  • 173
  • 2
  • 3
  • 9

5 Answers5

16

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);
Tomzan
  • 2,808
  • 14
  • 25
  • 3
    I don't know why, but this answer was downvoted even though it's the simplest answer of all and it works. It sets an interval and clears it after 10 seconds. That's exactly what it's supposed to do. – Butt4cak3 Sep 10 '13 at 13:09
6

Since startTime() will run every second, make a counter to increment to 10 inside of it, then clear the interval.

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

function startTime()
{
  if(counter == 10) {
    clearInterval(tt);
  } else {
    counter++;
  }

  document.getElementById('txt').innerHTML= counter;  
}

JSFiddle

Tricky12
  • 6,752
  • 1
  • 27
  • 35
3

Because you named a local variable named tt which does not let you access the global variable 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.

function checkTime(xtt)
{
if (xtt==10)
  {
    xtt="0" + xtt;
    console.log(xtt);
    clearInterval(tt);
  }
return xtt;
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
3

This works for me.

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

setTimeout(function() { clearInterval(tt); }, 10000);
Gynteniuxas
  • 7,035
  • 18
  • 38
  • 54
Sayid Dastaan
  • 47
  • 1
  • 2
0

you can do that

setInterval(startTime, 1000).pipe(takeUntil(timer(10000)));
itai schwed
  • 399
  • 4
  • 5