JavaScript setInterval Method | stop, loop examples

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

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.

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():

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:

Q: Can JavaScript setInterval stop itself?

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

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.