How to stop the timer after ten seconds in javascript using setInterval and clearInterval?

I was wondering how can I stop the timer after ten seconds in javascript using setInterval and clearInterval ?? Here is my sample code, could you tell me where I am 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> 
+4
source share
4 answers

Since startTime() will execute every second, make a counter to increase it to 10, 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

+4
source

you can set the timeout in the form like this right after setting the interval:

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

This works for me.

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

Since you named a local variable called tt, which does not allow you to access the global variable tt. Very poor variable name planning.

Your code will also not stop after 10 seconds, it will stop when the time is 10 seconds or 10 minutes.

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

Source: https://habr.com/ru/post/1501471/


All Articles