Skip to content

JavaScript timer loop | Example code

  • by

Use setInterval() to do the timer loop in JavaScript. It will repeat automatically until you clear the interval.

setInterval(myMethod, 5000);

function myMethod( )
{
  //this will repeat every 5 seconds
  //you can reset counter here
}

OR

setInterval(function(){ 
	console.log("Oooo Yeaaa!");
}, 2000);//run this thang every 2 seconds
  • setTimeout will execute the code once, after the timeout.
  • setInterval will execute the code forever, in intervals of the provided timeout.

Both functions return a timer ID which you can use to abort the timeout. All you have to do is store that value in a variable and use it as an argument to clearTimeout(tid) or clearInterval(tid) respectively.

So, depending on what you want to do, you have two valid choices:

// set timeout
var tid = setTimeout(mycode, 2000);
function mycode() {
  // do some stuff...
  tid = setTimeout(mycode, 2000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
  clearTimeout(tid);
}

or

// set interval
var tid = setInterval(mycode, 2000);
function mycode() {
  // do some stuff...
  // no need to recall the function (it's an interval, it'll loop forever)
}
function abortTimer() { // to be called when you want to stop the timer
  clearInterval(tid);
}

JavaScript timer loop

A simple example code calls a given function every n milliseconds. You could structure your countdown function like so:

<!DOCTYPE html>
<html>
<body>
  <script>
   function countdown(seconds) {
    var interval = setInterval(function() {

        if (seconds <= 0) 
        clearInterval(interval); //break the interval
        seconds--;
        
        console.log("Seconds:", seconds)
    }, 1000); //time in millaseconds to wait
  }

  countdown(5);
</script>

</body>
</html> 

Output:

JavaScript timer loop

How do I add a delay in a JavaScript loop?

Answer: Use something like this:

var i = 1;                  //  set your counter to 1

function myLoop() {         //  create a loop function
  setTimeout(function() {   //  call a 3s setTimeout when the loop is called
    console.log('hello');   //  your code here
    i++;                    //  increment the counter
    if (i < 10) {           //  if the counter < 10, call the loop function
      myLoop();             //  ..  again which will trigger another 
    }                       //  ..  setTimeout()
  }, 3000)
}

myLoop();                   //  start the loop

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS loop topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading