setTimeout vs setInterval

In Javascript world we usually come across scenarios where we want to execute a function after certain time. This is called as “Scheduling a function”. This can be achieved using setTimeout & setInterval methods. Both the functions are available on the window object.
setTimeout : Should be used if we want to execute the function only once after some time.
setInterval : Should be used if we want to execute the function continuously after specific time interval.
setTimeout : Following is the syntax for calling setTimeout

Parameters:
func|code : A function or callback to be passed to setTimeout which will be called once the delay is completed. Instead of function we can even pass strings which will be evaluated at runtime and executed. But the better way is to pass a callback or a function. This is a mandatory argument.
delay : Number of milliseconds after which the callback should be called. i.e. 3000 (for 3s), default is 0.
[arg1], [arg2], …additionalArgs : Additional arguments which needs to be passed as argument to the callback.
Example: Suppose if we want to show a alert after 3seconds, we can do in following way:


The return value of the setTimeout function is a TimerId which will usually be a number. This should be used if we want to clear the timeout. For clearing a timeout we can use clearTimeout function which will clear the timer.

setInterval : Similar to setTimeout, syntax of setInterval is also same just we need to call it with setInterval.

All the params have the same meaning as defined in setTimeout. As mentioned at the start, setInterval will continuously call the callback function after the specified delay. We can use clearInterval method for clearing the timer and It can be used in the same fashion as clearTimeout. It’s better to clear the interval as the callback function will be called infinitely.
SetInterval using SetTimeout: We can have a scenario where we need to call same callback but with different delays, These can be done using Nested setTimeout method.

Zero Delay setTimeout : We might have seen at lots of places where setTimeout is called with Zero (0) delay, i.e. We want to execute the callback function immediately. But the callback function will not be executed immediately, instead it will be called once the current running thread is completed. Please refer below screen shot for better understanding.

As shown in the screenshot even the delay is 0, that log statement will be printed after the for loop is completed.
Thanks for reading!