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. The time intervals are referred to 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. On the other hand, SetInterval is majorly used to execute a function after a certain time interval. The major difference between these two-time event functions is that the timeout function is executed only once after a particular time period. On the other hand, 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 is function used as settimeout(). It is used for executing a defined block of code after a specific time period, and the setTimeout function executes 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 which 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.
- No value or multiple values can be passed to the function when it runs.
- 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. The callbacks which are to be passed in these functions are called once the stack on the main thread becomes empty.
- 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 the code setTimeout(fn, 0) is executed, then after running a loop from 1 to 10 billion, the callback gets executed after some seconds.
- 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:
Code:
// 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);
This method of using setTimeout would be useful if the function has to be called from timeout as well as a response to an event. 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 time. However, it won’t be a good method if a function has to be called after a time interval again and again.
- 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 even pass any set of parameters which is required by a function for being executed 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.
Code:
function Time() {
let x = Date();
let time = date.toLocaleTimeString();
document.getElementById('demo').textContent = time;
}
const createWatch = setInterval(Time, 2000);
- The setInterval() also returns a value which can be used afterwards when the interval is required to remove, just like setTimeout().
- 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. It can be done in the same way; the time out is stopped. The way of doing it is to pass the identifier which was 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 towards 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 the 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:
setTimeout(<function name>, time in milliseconds) |
Syntax:
setInterval(<function name>, time in milliseconds) |
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
This is a guide to setTimeout vs setInterval. Here we discuss key differences with infographics and comparison tables, respectively. You may also have a look at the following articles to learn more –
41 Online Courses | 29 Hands-on Projects | 305+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses