JavaScript setTimeout() & setInterval() Method
Overview
In certain cases, we might feel the need to execute a function after a certain period of time. This process of executing a function at a particular time in the future or after a period of time is referred to as scheduling a call. There are two methods of scheduling a call in Javascript:
- setTimeout() in javascript
- setInterval() in javascript
In this article, we will see what these methods are and how to use them.
SetTimeout() Method
The setTimeout Javascript method is used to call a function after a certain period of time. The time after which the function will be called is given by the user in milliseconds.
Syntax
Let us now see the syntax of setTimeout() in javascript.
Parameter
There are two parameters that are to be passed to the setTimeout javascript method. One is the name of the function on which we want to apply the setTimeout javascript method, and the second is the time in milliseconds after which the above function is to be called.
Apart from these, there can be additional arguments. These are the arguments that are passed to the function being called.
Example
Here is an example of the setTimeout javascript method. Here we create a button, clicking on which pops up an alert. We apply javascript setTimeout to the function creating the alert and add a timer of 5000 seconds.
Output:
As soon as we press the "Click Here" button an alert box will pop up after 5000ms or 5 seconds, saying that "Here is an example of setTimeout javascript". It is because the purpose of the function demo is to pop up an alert, and we are applying setTimeout to that function with a timer of 5000 ms. So the target function is called after a gap of 5 seconds.
Canceling with ClearTimeout
We can cancel the timer by using the clearTimeout() function in javascript. For this, we need to store the timer identifier inside a variable, and pass this variable as an argument to the clearTimeout() method, and call it.
Let us see the syntax for canceling setTimeout() with clearTimeout():
SetInterval() Method
The setInterval Javascript method is used to call a function repeatedly at a specified interval of time. This time interval at which the function will be called is provided by the user in milliseconds.
Syntax
Let us now see the syntax of setInterval() in javascript.
Parameter
There are two parameters that are to be passed to the setInterval javascript method. One is the name of the function on which we want to apply the setInterval javascript method, and the second is the time in milliseconds, i.e the interval at which the function is to be called.
Apart from these, there can be additional arguments, that are passed to the function being called.
Example
Here is an example of the javascript setInterval() method.
Like the example discussed in setTimeout(), we create a button, clicking on which pops up an alert. We apply setInterval() to the function creating the alert and set it to an interval of 5000 seconds.
Output:
As soon as we press the "Click Here" button an alert box will pop up after every 5000ms or 5 seconds, saying that "Here is an example of setInterval Javascript". It is because the purpose of the function demo is to pop up an alert, and we are applying setInterval to that function with an interval of 5000 ms. So the target function is called and executed at every 5 seconds interval.
Canceling with ClearInterval
We can cancel the interval by using the clearInterval() function in javascript. For this we need to store the interval identifier inside a variable, and pass this variable as an argument to the clearInterval() method, and call it.
Let us see the syntax for canceling setInterval() with clearInterval():
Using setTimeout() Recursively
Instead of using the setInterval() method, we can also use the setTimeout() method recursively, especially if we want more control over when our delay starts.
setInterval() lacks in its ability to provide flexibility in modifying the interval timing after initial invocation. Eg - 10ms might have been appropriate for the first function call, but not for the subsequent ones. We won't be able to achieve this with setInterval(), since the interval provided is fixed.
Let us see how we can use setTimeout() recursively to achieve flexibility in our subsequent function calls.
Suppose we want to request data from a weather API, using the setTimeout() with an initial delay of 1 second. A request to the weather API is made every 1 second, with the help of the setTimeout() function. But in case, we fail to fetch the weather data from the API, maybe due to server overload or some other failures, we increase the delay of the setTimeout function by 1 second every time. We can code it in a recursive way as follows:
Explanation:
Here we are increasing the delay for the setTimeout() by 1 second, every time the request fails.
Another advantage of using recursive setTimeout() is that it allows us to set more precise delays between executions than setInterval() method.
Eg - If we allow 10ms interval in our setInterval() method, and the function takes 12 ms to execute, then the subsequent call will happen without any pause.
Whereas if we use recursive setTimeout() method, the 10 ms delay is guaranteed irrespective of whether the function takes more or less time to execute. The new call will always be scheduled after the end of the previous call.
Garbage Collection and SetInterval/SetTimeout Callback
We pass a function inside the setInterval/setTimeout callback, after which a reference to the function/object is created. This reference is saved in the scheduler as long as we can use the callback function i.e, the callback's lifespan. And this saved reference prevents the garbage collection of the function. Keeping the reference of function may lead to memory problems and to get rid of it we use clearInterval. Let's see how can we resolve this issue next with the help of clearInterval, which avoids the issue of prevention of reference of function which we may not need now.
We can use the clearInterval method in the following way:
Here intervalID stores the id returned by setInterval. We can use this intervalID to call clearInterval in the following way:
Hence it is always advisable to cancel the scheduled function if we are no longer using it, no matter how small or big it is.
Why You Might Need a Zero Delay SetTimeout?
Let us first understand what a zero delay setTimeout is. As you might have already guessed from the name itself, it refers to calling the setTimeout method with zero milliseconds as the second argument.
However, it is important to understand that zero delay setTimeout does not imply that the function will be executed after zero seconds.
The time after which the function will be executed in case of Zero delay, depends on the number of waiting tasks in the queue. The function will be executed only when all the other queued tasks are completed.
Now you might wonder why we need a Zero delay setTimeout.
Sometimes we might need to schedule a callback after the shortest or minimum delay possible. Or, we might need to schedule a function execution as soon as possible but only after the current script is completed. In such cases, zero delay setTimeout comes handy, as zero delay setTimeout will schedule the function call immediately after the current script is completed.
Things to Keep in Mind about SetTimeout() and SetInterval()
- The browsers supported by setTimeout() and setInterval() are Google Chrome, Internet Explorer, Firefox, Opera, Safari.
- Nested setTimeout calls allow us to set the time between two executions more precisely than setInterval.
- Nested setTimeout calls are more flexible than setInterval.
- If there are more than 5 nested setTimeout calls, the browser limits the minimum delay to 4ms.
- Zero delays setTimeouts schedule the function call as soon as possible after the current script is completed.
Conclusion
- setTimeout() and setInterval() methods in Javascript allow us to run our code asynchronously (Program doesn't need to wait for a task to complete before moving on to the next task).
- The setTimeout() method is used to call a function after a certain period of time.
- The setInterval() Javascript method is used to call a function repeatedly at a specified interval of time.
- setTimeout() is cancelled by clearTimeout() method, and setInterval() is cancelled by clearInterval() method.
- Recursive setTimeout() is used instead of setInterval() if more control over the delay start time is desired.
- setTimeout() and setInterval() saves the reference of a function which prevents garbage collection. To avoid it, we use clearInterval().