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


	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


// 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

JavaScript timer loop

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

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

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




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


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


Leave a Reply

Your email address will not be published. Required fields are marked *