Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?? 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>
like image 325
Formula 1 Avatar asked Nov 27 '22 14:11

Formula 1


2 Answers

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);
like image 199
Tomzan Avatar answered Dec 04 '22 07:12

Tomzan


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

like image 20
Tricky12 Avatar answered Dec 04 '22 08:12

Tricky12