How setInterval works in JavaScript

JavaScript has timers that developers can leverage to execute the code asynchronously. These are setInterval, clearInterval, setTimeout and clearTiemout. In this video, you will learn about setInterval and clearInterval.

You will learn why the delay provided as an argument is not a guaranteed delay. In fact, it is the least amount of delay between the recurring function calls as demonstrated in the example.


var colors = ["#1AB399", "#66E64D", "#6666FF", "#E666B3", "#FF3380", "#B3B31A",
"#FF4D4D", "#33991A", "#809980", "#4DB3FF", "#999933", "#99E6E6", "#CC9999",
"#E666FF", "#CCCC00", "#4DB380", "#4D8066", "#991AFF", "#E6FF80", "#00E680",
"#9900B3", "#4D80CC", "#66664D", "#1AFF33", "#E64D66"];
let changeColor = function () {
let newColorIndex = Math.floor(Math.random(colors.length) * 10)
let newColor = colors[newColorIndex] = newColor
let intervalId = setInterval(changeColor, 1000)
// clearInterval(intervalId) // to clear the interval

Full Transcript

0:00 Hello there It's Harit from bonsaiilabs. In today's JavaScript session, we will learn what set into is and how it works. There are timers implemented by browsers such as Google Chrome, and the implementation of one browser may differ from another one such as Safari or Firefox. Today we're specifically going to focus on setInterval and clearInterval. So what does setInterval means? If you focus on what interval is, it is indicated by the space in time between events, but what are events? In the context of setInterval, it means the function that you would execute after a specified interval. This interval is also known as delay. So in essence, setInterval is used to execute a function repeatedly after a specified delay. Now, one thing to note is that the specified delay is the least amount of delay that would occur between the function calls.

0:55 In other words, the delay that we specify does not guarantee that the repeated function calls would occur exactly after the specified delay. Let me show you why. Let's say our task at hand is to change the background color of the window after every 200 milliseconds. Let's call this function changeColor. Next, let's create a timeline so that we can track the events on the timescale. Now JavaScript runs on the main thread, which means only one code block and execute at a time. Any other code block must wait in a task you before the main third has a bandwidth to pick another task. We have created a task queue to demonstrate the pending tasks here. Now let's say at times zero we executed setInterval and told it to execute changeColor function after every 200 milliseconds. Now don't worry about the complete code. We will write it in few moments from now, but here I'm trying to show why the delay is not guaranteed and it is the least amount of delay between the function calls.

1:54 Now after 200 millisecond pass, the timer will invoke and the changeColor will sit in the task queue. At this time since the main thread is available to do the work, it will immediately execute the changeColor and will change the color of the window. Now let's say time 300 the user uploads the file. At this time, the main thread is done executing changeColor function and moves to start execution of upload file function. While the main thread is working, the setInterval timer invokes again and it's time to execute the changeColor function, right? So the changeColor function will now sit in the task queue and wait for the main thread to execute it. So as you see, the code execution is not guaranteed at the exact interval because the main thread is busy uploading the file. Now, let's say time 500 millisecond, the file upload completes and it is now the time that the main thread will execute the changeColor function.

2:48 So the delay is only guaranteeing the minimum amount of delay between the two events and once it execute, it changes the color of the window. Then at time 600 millisecond, the timer invokes again and the changeColor is added to the task queue. Since the main thread is available to execute JavaScript code, it will execute the function immediately causing the color of the window to change again. Okay, I hope that gave you some idea of how setInterval works. Let's write the code next for this exercise. I'm now here in Google Chrome and opened up this in guest window. The first thing I will do is open up the developer tools and open up the console window. Next I will type window and hit enter. If I open the window object, there are lot of objects you will see as you scroll a little bit down and try to locate the timers,

3:38 you will see all the timers that we have discussed in the window object. Next, I will clear the screen and create an array called colors which contains the hex code of some random colors. Next, I will create a function called changeColor. As you see it is doing three things. In the first line, it uses math.random to pick a random index from zero to the length of the array. In the next line we pick a random color based on the index that we have found and pick the color from the colors array. And finally in the third line I'm setting up the body style background color for the Google webpage with the new color. Now we are ready to call setInterval. So we will say setInterval and the first argument is the handler, which is the function we want to execute, which is changeColor.

4:32 The second argument is the timeout, which is the timeout in milliseconds. So for one second we are going to provide thousand milliseconds and as we hit enter we will see that after every second the background color for the Google webpage is changing. Now how do we stop if w want to stop this interval? For that, if you notice that setInterval returns an ID, which is a number. So, we can use clearInterval and pass in the ID returned by setInterval which is 28 and we close it and as we run you will see that now the change of the background color is not happening anymore. You can call in as many setInterval as you want. So I ran one more setInterval with 500 milliseconds. And as you see that the page color changes more frequently, and I got a new interval ID, which I can use to clear the interval and stop changing the color again. And that's it. If you like the video, consider subscribing us to receive more engaging content about JavaScript every single week. Until then, keep learning new skills and apply them regularly to become an expert programmer. See you next time.