Tuesday, August 28, 2018

javascript - setTimeout or setInterval?




As far as I can tell, these two pieces of javascript behave the same way:



Option A:



function myTimeoutFunction()
{
doStuff();
setTimeout(myTimeoutFunction, 1000);
}


myTimeoutFunction();


Option B:



function myTimeoutFunction()
{
doStuff();
}


myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);


Is there any difference between using setTimeout and setInterval?


Answer



They essentially try to do the same thing, but the setInterval approach will be more accurate than the setTimeout approach, since setTimeout waits 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 your function takes a long time to execute).



Altough one might think that setInterval will execute exactly every 1000ms, it is important to note that setInterval will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish.




In this Fiddle, you 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 you 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, you should go for a self-adjusting timer (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created)


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...