setInterval is a JavaScript command which takes two parameters. The first is the name of a function and the second is the time interval, in milliseconds, that this function should be repeatedly called.

For example:

<html>
  <body>
    <p id = "counter"></p>
    <script>
      i = 0;
      setInterval(update,10);
      function update() {
        i++;
        document.getElementById('counter').innerHTML = i;
      }
    </script>
  </body>
</html>

In this code, setInterval calls the function ‘update’ every 10 milliseconds. The function increases the variable i by 1 and displays the value in the paragraph with the id of ‘counter’.

Things to watch out for

  • Make sure that you list the function name before the time
  • Do not include parentheses after the function name. In other words, do not use:
setInterval(update(),10);

Related functions

clearInterval() – this stops the function from being called again. It is used like this:

<html>
  <body>
    <p id = "counter"></p>
    <button id = "stop" onclick = "stop()">Stop</button>
    <script>
      i = 0;
      updateInterval = setInterval(update,10);
      function update() {
        i++;
        document.getElementById('counter').innerHTML = i;
      }

      function stop() {
         clearInterval(updateInterval);
      }
    </script>
  </body>
</html>

Note that a variable (‘updateInterval’ in this case) is used to keep track of what interval we will want to clear later.

setTimeout() is used like setInterval() except that setTimeout() calls the function only once.

clearTimeout() can be used to stop setTimeout() from calling the function.

References

JavaScript Timing Events (w3schools.com)

Comments

Leave a comment