Javascript Reference - Window setInterval() Method








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

setInterval() executes the code repeatedly at specific time intervals until the interval is canceled or the page is unloaded.

The setInterval() method accepts:

  • the code to execute
  • the milliseconds to wait between executions.
<!DOCTYPE HTML> 
<html> 
    <body> 
        <script type="text/javascript"> 
            setInterval(function() { <!--from w  w w  .  ja va2  s  .  c  o  m-->
                document.writeln("Hello world!"); 
            }, 1000); 

        </script> 
    </body> 
</html>

Click to view the demo





Browser Support

setInterval Yes Yes Yes Yes Yes

Syntax

setInterval(function,milliseconds,lang)

Parameter Values

Parameter Description
function Required. The function to call
milliseconds Required. The intervals in milliseconds to execute the code
lang Optional. JScript | VBScript | JavaScript




Return Value

An integer ID value of the timer.

Example

The following code shows how to display the current time every second.


<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myVar = setInterval(function(){myTimer()}, 1000);
<!--from  w  w w. j a v a  2s.  com-->
function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}
</script>

</body>
</html>

The code above is rendered as follows:

Clear the timer

The setInterval() method returns an interval ID. We can use the ID to cancel the interval with clearInterval() method.

<!DOCTYPE HTML> 
<html> 
    <body> 
        <script type="text/javascript"> 
            var num = 0; 
            var max = 10; 
            var intervalId = null; 
            function incrementNumber() { 
                document.writeln(num++);
                //if the max has been reached, 
                //cancel all pending executions 
                if (num == max) { 
                    clearInterval(intervalId); 
                    document.writeln("Done"); 
                } <!--   w ww .  j a  v  a 2  s. c  o  m-->
            } 
            intervalId = setInterval(incrementNumber, 500); 


        </script> 
    </body> 
</html>

Click to view the demo