- They essentially try to do the same thing, but the
setIntervalapproach will be more accurate than the
setTimeoutwaits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if our function takes a long time to execute).
- Altough one might think that
setIntervalwill execute exactly every 1000ms, it is important to note that
- we can clearly see that the timeout will fall behind, while the interval is almost all the time at almost 1 call/second (which the script is trying to do). If we change the speed variable at the top to something small like 20 (meaning it will try to run 50 times per second), the interval will never quite reach an average of 50 iterations per second.
- The delay is almost always negligible, but if you're programming something really precise, we should go for a self-adjusting timer (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created)
- setInterval() is a time interval based code execution method that has the native ability to repeatedly run a specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless we call clearInterval().
- If we want to loop code for animations or on a clock tick, then use setInterval().
setTimeout() is a time based code execution method that will execute a script only one time when the interval is reached. It will not repeat again unless we gear it to loop the script by nesting the setTimeout() object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless we call clearTimeout().
If we want something to happen one time after a specified period of time, then use setTimeout(). That is because it only executes one time when the specified interval is reached.
The setInterval makes it easier to cancel future execution of our code. If we use setTimeout, we must keep track of the timer id in case we wish to cancel it later on.
We find the
setTimeout method easier to use if we want to cancel the timeout:
Also, if something would go wrong in the function it will just stop repeating at the first time error, instead of repeating the error every second
The very difference is in their purposes.
- It's as simple as that more elaborate details here