How to use setInterval() and clearInterval() in JS

Introduction to setInterval.....

ยท

3 min read

How to use setInterval() and clearInterval() in JS

Today we are going to talk about the basic working of setInterval and clearInterval methods in JavaScript

They are very important in terms of their application.

The setInterval() is a function that runs a piece of code after some regular interval of time. It will continue to run until the termination condition is not executed.

The termination is done by clearInterval() carbon.png

The setInterval takes 2 arguments

  1. Function or method that to be performed after regular interval
  2. The time of interval.

This piece of code given above will execute

alert("hello") after every 1000 milisec.(1 second) untill clearInterval() for this setinterval() is not executed.

setInterval returns a random value which can be considered as its ID by using this id we can terminate it ,lets look at the code

``` var a = setInterval(Timer, 1000);

function Timer() {
  alert("hello world i am Nooob")
}

function clear() {
  clearInterval(a);
}

```

Using the id of setInterval ,clear() will terminate the execution flow , Here Timer function is the action to be performed after 1 second.Whenever clear() is called it will end up the ongoing execution of setInterval mentioning the ID.

The above given code will continue to give alert until the function clear() is not called. This can be done on events like onClick, onFocus

Hope this will help you to understand ....in next we will talk about How to make Timer using setInterval

Feedback and Questions

If you got any questions or want to add your thoughts? Let me know in the comments below, please.

Share

If you like this Blog please share to your friends and colleagues..

Thanks