Sometimes we need such functionality that a function can be run again after some time. One use case is that we have a clock and we need the time to be updated every second. And the second use case is that we are making an image slideshow or carousel and we need the image to change after every few seconds. In this use case we use the setInterval
function.
setInterval(function(){
let date = new Date();
console.log(date.toLocaleTimeString());
},1000)
When we run the above function, it will keep printing the time in the console every second.
SetInterval: This function takes two arguments, the first argument is a function we need to run after each interval. The second argument is time which tells after how much time the passed function should be run again. Keep in mind that the time we pass as an argument is in milliseconds, hence 1000 is written in the above example. 1000 millisecond = 1 second
Now you will say that this function will run continuously, can it be stopped? What has been started can also be stopped. To stop setinterval
function we use clearInterval
function. This function takes the Interval Id
as argument, because the clearInterval
function needs to know which interval to stop. But now you might be asking, "Where do I find the interval Id?". Don't stress, it is very simple, whenever we run the setInterval
function it returns the interval Id
and we will store it in a variable and pass it to the clearInterval
function.
let intervalId = setInterval(.....)
clearInteval(intervalId)
The above code was to give you a high level understanding of these functions, now I will try to explain these functions with a real life example.
Now we will create a web page which will have 2 elements, in it a div
will show the time which will be updated every second, and a button
which will stop updating the time on click.
<div class="clock">00:00</div>
<button class="button">Pause</button>
let clock = document.querySelector(".clock");
let button = document.querySelector(".button");
function changeDate() {
let date = new Date();
clock.innerText = date.toLocaleTimeString();
}
let interval = setInterval(changeDate, 1000);
function stopTime() {
clearInterval(interval);
}
button.addEventListener("click", stopTime);
let clock = document.querySelector(".clock")
- In this line we are selecting an element using
querySelector
whose class attribute's value isclock
, its reference will be assigned to theclock variable
.
- In this line we are selecting an element using
let button = document.querySelector(".button")
- In this line we are selecting an element using
querySelector
whose class attribute's value isbutton
, its reference will be assigned to thebutton variable
.
- In this line we are selecting an element using
changeDate(){...}
- This function will first create a new object of the
Date
class, and then the time returned fromdate.toLocaleTimeString()
will be inserted into theinner text
of the clock element.
- This function will first create a new object of the
let interval = setInterval( changeDate , 1000);
In this line, in the
setInterval
function, we have passed thechangeDate
function that we need to run after every 1 second, the second argument is time (1000). This is 1000 milliseconds which is equal to 1 second. Meaning the function passed (i.e. change date) should run after every 1 second.The
setInterval
function will start running immediately, and will return aninterval ID
that will be assigned to theinterval
variable.
function stopTime(){...}
- Whenever this function executes, it will call the
clearInterval
function passing theinterval ID
that is assigned to the interval variable. Running this will stop the interval started with thesetInterval
function, and stop the clock from updating the time.
- Whenever this function executes, it will call the
button.addEventListener("click", stopTime);**
- In this line, we are adding an
event listener
to our button element, which will call thestoptime
function when the button is pressed. Which eventually stops the clock updating the time.
- In this line, we are adding an
In summary, the setInterval
function in JavaScript is a powerful tool for executing code at specified intervals. It's particularly useful for tasks like updating clocks, creating animations, or automating repetitive processes on web pages. By understanding how setInterval
works in conjunction with clearInterval
, you gain control over the timing of your functions, ensuring they execute precisely when needed.
With practice and exploration, you'll master the art of timing in JavaScript, harnessing the setInterval
function to enhance the functionality and user experience of your web applications.
Here's a link to the example code.
Keep coding, keep learning, and enjoy the journey of building with JavaScript!