setTimeout() vs setInterval() in JavaScript
Let's look at the difference between setTimeout() and setInterval() functions in JS.
13 September, 2022
19
19
2
Contributors
Often times, people get confused between when to use the setTimeout() and setInterval() functions in JavaScript. Hence, in this article let us take a look at how these two differ from one another in their applications.
setTimeout()
setTimeout() is an asynchronous javascript function that allows us to execute a particular function after a certain period of time. In other words, it allows you to trigger a particular action at a given moment in time.
Asynchronous: means that an operation can occur while another one still being processed.
The syntax looks like this,
The first parameter of setTimeout() takes the function that you want to execute. And, the second parameter is to specify after what time, this particular function has to be executed.
The conventional way of writing this code is as below, where we don't specify the name of the function but keep the name of the function anonymous. Again, this is just a convention and you can code either way.
this can be also written using the arrow function as,
Here, the setTimeOut() function will print Hello after 2 seconds (2 seconds = 2000 milliseconds) after the function is executed.
Note: In case you omit the second parameter, that is the time parameter, then the setTimeout() will execute the function at the very instant without waiting at all.
A practical example can be a situation where you want to set an alarm after 5mins.
setInterval()
It works similarly to the setTimeout() but the function will run repeatedly, starting after the interval of time mentioned, then repeating continuously at that interval.
The syntax of setInterval() looks similar to setTimeout(), the only difference is that there is setInterval() in place of setTimout().
Syntax:
The first parameter of setInterval() takes the function that you want to execute. And, the second parameter is to specify after what interval of time, this function has to be executed repeatedly.
Here, the setInterval() function will print
And it goes on until it is stopped using the clearInteral() function.
A practical example of setInterval() is in Twitter bots where the tweets have to be scheduled after a particular time interval. Another example could be a timer in a game that counts from 10 to 1 with 1 second of delay.
That's all folks. Thank you for reading!
I hope it was a small helpful article for you to understand the difference between setTimeout and setInterval. If you have any questions, don't hesitate to ask in the comments. Do give a like and share the article if you find it helpful!
javascript
blogging