What is setInterval() method in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

setInterval()

This is one of the many timing events. The window object allows code to execute at every certain interval of time. This object has provided SetInterval() to repeat a function for every certain amount of time. It takes two parameters as arguments. One is the function and the other is the time that specifies the interval after which the function should be repeated.

syntax

window.setInterval(function, milliseconds, param1, param2, ...));

This method can also take other parameters and can add it to the function.

Example-1

In the following example, setInterval() method is defined and a time interval of 3000 millisecs or 3 seconds is declared. Therefore the function provided inside it will repeat for every 3 secs. The result, for a time span of 9 secs, is showed in the output.

Live Demo

<html>
<body>
<script>
   setInterval(function(){
      document.write("Tutorix </br>");
   }, 3000);
</script>
</body>
</html>

Output

Tutorix
Tutorix
Tutorix


Example-2

In the following example, setInterval() method is defined and a time interval of 2000 millisecs is declared. Therefore the function provided inside it will repeat for every 2 secs. The result is showed in the output.

Live Demo

<html>
<body>
<script>
   setInterval(function(){
      document.write("Hello </br>");
   }, 2000);
</script>
</body>
</html>

Output

Hello
Hello
raja
Published on 05-Aug-2019 11:53:58
Advertisements