Updated May 6, 2023
Difference Between setTimeout vs setInterval
The following article provides an outline for setTimeout vs setInterval. JavaScript has two main timing events, which are setTimeout and setInterval. The window object of JavaScript enables the execution of codes at a particular interval of time. We refer to the time intervals as time events. The two major methods used in JavaScript are setTimeout and setInterval. The major work of setTimeout is to execute the function after waiting for a certain time. The setInterval function is primarily used to execute a function after a specific time interval, while the timeout function is executed only once after a particular time period. The significant difference between these two time event functions is that the setInterval function is used continuously after a specific time interval.
Head to Head Comparison Between setTimeout vs setInterval (Infographics)
Below are the top 4 differences between setTimeout vs setInterval:
Key Difference Between setTimeout vs setInterval
Let us discuss some of the major key differences between setTimeout vs setInterval:
1. SetTimeout
The setTimeout() function is a method used to execute a specific block of code after a certain period of time. It is called using the setTimeout() method and will execute the code block only once after the specified time. Once the time has elapsed, it won’t call the code again.
The setTimeout function takes the following parameters:
- First, it needs to have a function or a reference pointed to another function defined somewhere in the complete code.
- It needs to have a number that would represent the time interval in milliseconds, where 1000 milliseconds are equal to 1 second. This time interval signifies the amount of time the program has to wait to execute a certain code block. If 0 seconds is mentioned in the place of the value, then the function would run as quickly as possible.
- When the function runs, it can be executed with either no value or multiple values passed to it.
- The time which is specified in the place of time interval does not ensure that the function will be executed by that time. However, it is the minimum time after which the function may get executed. Once the stack on the main thread becomes empty, the functions will call the callbacks that were passed to them.
- If we write the code as setTimeout(fn,0), then the code will be executed as soon as the stack gets empty but not immediately. If you run the code setTimeout(fn, 0), the callback won’t execute for a few seconds until a loop from 1 to 10 billion has completed.
- Like for example, if we execute this code:
let Join = setTimeout (() => { alert ('Congratulations, you have joined EDUCBA');}, 5000);
- Here the browser will wait for at least 5 seconds, and then it would call the anonymous function followed by the alert message, “ Congratulations, you have joined EDUCBA”.
- The function doesn’t have to be always anonymous. We can put any function name there and define the function anywhere in the complete code. Of course, we will have to pass a reference to the code with setTimeout().
Example:
// Here we would put a function name
let Join = setTimeout(function Ackowledgement() {
alert('Congratulations, you have joined EDUCBA ');
}, 5000);
// The function is defined here
function Acknowledgement() {
alert(' Congratulations, you have joined EDUCBA ');
}
let Join = setTimeout(Acknowledgement, 5000);
Using setTimeout in this way can be useful when the function needs to be called both in response to an event and after a certain timeout period. Moreover, it will also help in keeping the code tidy, even in the case of having a callback timeout with multiple lines of code.
2. SetInterval
- setTimeout() is a very good method to use if we have to run a code only once after a defined set of times. However, using setInterval() repeatedly to call a function after a time interval is not a good approach.
- Here comes the role of setInterval(). The setInterval() has the same working of setTimeout() but with a slight difference. The difference is that now the code has to run again and again after a specified time interval. We can pass any set of parameters required by a function for execution as the parameters of the setInterval() method.
- Here we will see an example. In this example, the function would create a Date() object by extracting a time string by using toLocaleTimeString(). It would then display the date in the user interface. Now the function would run after every two seconds by using setInterval(), which would act as a digital clock that can update after every second.
Example:
function Time() {
let x = Date();
let time = date.toLocaleTimeString();
document.getElementById('demo').textContent = time;
}
const createWatch = setInterval(Time, 2000);
- Like setTimeout(), setInterval() also returns a value that can be used later when the interval needs to be removed.
- If we want to run a task forever, then setInterval() is our solution unless we stop it from running. We also have a way to stop the setInterval() method for preventing continuous errors once the system exceeds the capability of executing the function or the task has finished. You can stop the setInterval function in the same way as the timeout function by passing the identifier returned by the setInterval method to the clearInterval() method.
- If we are using setTimeout() recursively, then every iteration has to calculate a different interval of time to move toward the upcoming iteration.
setTimeout vs setInterval Comparison Table
Let’s discuss the top comparison between setTimeout vs setInterval:
setTimeout |
setInterval |
This is a time event function used to call another function after a certain time period, but it executes the function only once. | SetInterval function is the same as setTimeout with a slight difference. Here the setInterval function calls a function after a specific time period, but the execution occurs continuously according to the specified time interval. Here the time interval works like a time gap after which the function has to call another function every time. |
The setTimeout function calls the required block of code only once. | The setInterval function calls the required code after the particular time interval provided, again and again. |
For clearing the timeout function, one has to use cleartimeout(). | For clearing the setInterval function, one has to use clearInterval(). |
Syntax:
|
Syntax:
|
Conclusion
On the basis of the above article, we understood the two functions of time event: setTimeout and setInterval. According to our requirement, we went through the key difference they have in between and how to use setTimeout and setInterval.
Recommended Articles
We hope that this EDUCBA information on “setTimeout vs setInterval” was beneficial to you. You can view EDUCBA’s recommended articles for more information.