JavaScript: using setInterval()

In this post I'm going to show you how to use the JavaScript setInterval() function to create repeated animations. This function accepts two arguments: the former is the callback function to be executed and the latter a time delay expressed in milliseconds. The problem with this function, and with all the JavaScript timers in general, is that they must be reset after a certain period to prevent them from using too many resources. We're going to use the clearInterval() function for that purpose, which accepts as its sole argument the ID of the timer to be cleared, that is, a reference to the timer itself. Let's see how to implement this:

window.onload = function() {

      var test = document.getElementById('test');
      var counter = 0;  

      var interval = setInterval(function() {

        counter += 1;

        test.innerHTML += counter.toString() + '  ';

        if(counter == 10) {
           clearInterval(interval);

        }

      }, 1000);

};

This timer, referenced as interval, adds a progressive number to a page element every second. When this timer equals to 10, we reset it by calling the clearInterval() function by passing it a reference to the timer. You can see a demo below.

Demo

Live demo

Comments are closed.