JavaScript setInterval: Method to Execute The Code At Certain Time Interval.

0

In this blog post you’ll learn the javascript method that executes the function again and again at a given time interval which is the setInterval() method.


learn to run code at a given or defined interval of time using JavaScript method called setInterval Method. And Learn to clear or pause or stop the setInterval method.


setInterval Method.

Syntax:


JavaScript


    setInterval(function, milliseconds);
  

  • function required. You can call or define the function.
  • milliseconds required. Its for the time, that function will call at given time interval.


You can also write like this.


JavaScript


    // syntax:
    setInterval(function() {
        //code
    }, milliseconds);
    
    // Arrow function.
    setInterval(() => {
        //code
    }, milliseconds);
  

Description:

setInterval() method is used to call or execute the function at a defined interval (milliseconds).


The time is defined in milliseconds. For example, If you want to execute the code every three seconds you can write 3000 milliseconds to execute the code after 3 seconds.


It executes the code given inside, again and again until the window closes or the clearInterval method is called.


Example:

Simple automatic counter


JavaScript


    let i = 0;
    setInterval(() => {
        document.write(i++);
        document.write("<br>");
    }, 1000);
  


clearInterval Method.

To stop the setInterval method from executing the code again and again you can use another javascript method which is clearInterval().


Syntax:


JavaScript


clearInterval(myinterval);
  

Here, myinterval is a variable name in which the setInterval method is store which we want to clear or stop.


Store the setInterval method inside the variable. Then add that variable name inside the clearInterval() method (like this clearInterval(variable name)).


Example:

In this example we'll print or write the number in document till 10. After 10 we'll clear the interval.


JavaScript


    let i = 0;
    let myinterval = setInterval(() => {
        if (i == 10) {
            clearInterval(myinterval);
        }
        document.write(i++);
        document.write("<br>");
    }, 1000);
  


So that's it for the setInterval() method. Its use to run or execute the code at a given time interval (in milliseconds). If you have any querys or suggestions feel free to write on the comment section.

Tags

Post a Comment

0Comments

Share your thoughts.

Post a Comment (0)
To Top