[ Web Proxy ]
URL:
Viewing: https://www.javascripttutorial.net/javascript-bom/javascript-setinterval/ [Back]  [Original]

JavaScript setInterval Demo
Skip to content

JavaScript setInterval

Summary: in this tutorial, you will learn how to use the JavaScript setInterval() to repeatedly call a function with a fixed delay between each call.

Introduction to JavaScript setInterval()

The setInterval() is a method of the window object. The setInterval() repeatedly calls a function with a fixed delay between each call.

The following illustrates the syntax of the setInterval():

let intervalID = setInterval(callback, delay,[arg1, arg2, ...]);
Code language: JavaScript (javascript)

In this syntax:

The setInterval() returns a numeric, non-zero number that identifies the created timer. You can pass the intervalID to the clearInterval() to cancel the timeout.

Note that the setInterval() works like the setTimeout() but it repeatedly executes a callback once every specified delay.

JavaScript setInterval() example

The following example uses the setInterval() and clearInterval() to change the color of a heading once a second once you press the Start button. If you stop the button, the clearInterval() will cancel the timeout.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>JavaScript setInterval Demo</title>

  <script>
    let intervalID;
 
    function toggleColor() {
      let e = document.getElementById('flashtext');
      e.style.color = e.style.color == 'red' ? 'blue' : 'red';
    }

    function stop() {
      clearInterval(intervalID);
    }

    function start() {
       intervalID = setInterval(toggleColor, 1000); 
    }
  </script>
</head>
 
<body>
  <p id="flashtext">JavScript setInterval Demo</p>
  <button onclick="start()">Start</button>
  <button onclick="stop()">Stop</button>
  
</body>
</html>Code language: HTML, XML (xml)

Output:

JavaScript setInterval Demo

Start Stop

Summary

Was this tutorial helpful ?
Yes No
Search &hellip;:

Window

Location

Navigator

Screen

History

Copyright © 2009 - Present by JavaScript Tutorial Website. All Right Reserved.


Web Proxy Viewer  |  New URL  |  Original Page