So I know that there are differences between setTimeout and setInterval, but consider these two code examples:
function myFunction(){
setTimeout('myFunction();', 100);
doSomething();
}
setTimeout('myFunction();', 100);
and
function myFunction(){
doSomething();
}
setInterval('myFunction();', 100);
Note that in the first example I call setTimeout at the begining of the function and then I doSomething. Therefore there is no extra delay from doSomething(). Does that mean that those two examples do exactly the same? Or is there even more subtle difference?
They’re functionally about the same, but there are differences. One difference is in how browsers handle it if
doSomethingtakes longer than the interval. WithsetInterval, at least some browsers will just skip the next interval ifdoSomethingis still running. So if you use 100ms as you have, anddoSomethingtakes 110 ms to run, the next run won’t happen until 90ms later (of course, all of these times are approximate).Another difference is that with the
setTimeout, you’ll get a new handle every time, whereas withsetIntervalyou get one handle.Another difference with your examples as given is that in the
setTimeoutexample, you’re firing up a JavaScript parser/compiler every time, whereas withsetIntervalyou’re only firing up the parser/compiler once. But this difference shouldn’t matter, because you shouldn’t be doing that at all — see below.But subtleties aside, what you have there is functionally the same.
Side note: It’s not best practice to pass strings into either
setTimeoutorsetInterval. Instead, pass in a function reference:Passing in a string fires up a JavaScript parser and does the same thing as
eval. It should be avoided whenever possible (and it’s almost always possible).