Skip to content

JavaScript setInterval Method | stop, loop examples

  • by

JavaScript setInterval method evaluates an expression at specified intervals (in milliseconds). You need to clearInterval() method to stop the setInterval() method.

Note: 1000 ms = 1 second.

If you want to execute a function only once Then use the setTimeout() method.

Syntax

setInterval(function, milliseconds)

Parameter Values

  • function:- The function that will be executed
  • milliseconds:- The intervals (in milliseconds) on how often to execute the code.

Examples of JavaScript setInterval Method

After every second a new “Hello” message will be displayed. You need to close the window to stop interval execution in this example.

<!DOCTYPE html> 
<html> 
  
<body> 
  
  
    <p id="EHS"></p> 
  
    <script> 
        var myVar = setInterval(sTimer, 1000); 
  
        function sTimer() { 
            document.getElementById("EHS").innerHTML += "<p>Hello</p>"; 
        } 
    </script> 
  
</body> 
</html> 

Output:

Examples of JavaScript setInterval Method

How to JavaScript setInterval stop

Use clearInterval() method to stop setInterval(). setInterval() returns an interval ID, which you can pass to clearInterval():

var refreshIntervalId = setInterval(fname, 10000);

/* later */
clearInterval(refreshIntervalId);

JavaScript setInterval loop

How do I do it if I only want the function to be ran 10 times.

Simply, Just use a counter which increments each time the callback gets executed, and when it reaches your desired number of executions, use clearInterval() to kill the timer:

var counter = 0;
var i = setInterval(function(){
    // do your thing

    counter++;
    if(counter === 10) {
        clearInterval(i);
    }
}, 200);

Q: Can JavaScript setInterval stop itself?

Answer: As long as you have scope to the saved interval variable, you can cancel it from anywhere.

var myInterval = setInterval(function() {
  if (/* condition here */){
        clearInterval(myInterval);
   } 
}, 50);

Do comment if you have any doubts and suggestion on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading