JavaScript setInterval() Method

You are Here:

JavaScript setInterval() Method

The setInterval() method calls a function at specified intervals (in milliseconds).

Note: Unlike setTimeout(), the setInterval() method will continue calling the function until clearInterval() method is called, or the window is closed.

The following example will call the function (myCountDown()) for every second.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Start Count Down</button> <p id="point"></p> <script> var count = 0; var x = document.getElementById("point"); function myFunction(){ setInterval(myCountDown, 1000) } function myCountDown(){ count = count + 1; x.innerHTML = count; } </script> </body> </html>

Syntax

setInterval(function, gap, param1, ..., paramN); //or setInterval(function, gap);

Parameter Values

ValueTypeExplanation
functionRequiredSpecifies a function to be executed.
gapOptionalSpecifies a time interval in millisecond.
If omitted, the default value is 0.
Note: 1000ms = 1sec.
param1, ..., paramNOptionalSpecifies the additional parameters to pass to the function.
Param is not supported in IE9 and earlier.

setInterval() with Self Function

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Start Count Down</button> <p id="point"></p> <script> var count = 0; var x = document.getElementById("point"); function myFunction(){ setInterval(function(){ count = count + 1; x.innerHTML = count; }, 1000) } </script> </body> </html>

setInterval() with Optional Parameter

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Start Count Down</button> <p id="point"></p> <script> var count = 0; var x = document.getElementById("point"); function myFunction(){ setInterval(myCountDown, 1000, myMessage()) } function myCountDown(){ count = count + 1; x.innerHTML = count; } function myMessage(){ alert("I will Execute once"); } </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author