Help Chosing Between Settimeout And Setinterval
Solution 1:
It's totally personal preference. setInterval
has some odd edge cases around what happens when the previous interval's code hasn't finished running before the next interval is due to start (not a problem if your interval is every minute; intervals every second, which one sometimes wants, get a bit tricky).
I tend to prefer chained setTimeout
calls (where each schedules the next) because they can't run away with you — your code always has to explicitly say "Okay, and call me back again next time." But properly-written code should work with either.
Chained setTimeout
calls are also more well-suited to asynchronous operations, like for instance polling something via ajax, because you don't schedule the next timeout until the ajax operation completes. Using setInterval
, because the ajax calls are asynchronous, you could end up overlapping them.
Solution 2:
Using setinterval
would be the more natural choise. If you use setTimeout
, you have to start a new timeout from the event handler.
window.setInterval(get_reported_incidents, 60*1000);
Solution 3:
setTimeout
runs a command once after a period of time. setInterval
runs a command every time interval.
So, to run get_reported_incidents
every minute use setInterval
.
var interval = setInterval(get_reported_incidents, 60000);
Solution 4:
setinterval executes a function at a given interval. settimeout executes a function after a specified wait time, and then exits.
If you are attempting to do a cron-like execution every minute, you will want to use setinterval.
Please see http://javascript.about.com/library/blstvsi.htm for a comparison.
Solution 5:
use setTimeout
recursively. See here for more information on why setInterval
is a poor choice.
function timeout (){
get_reported_incidents();
setTimeout(timeout, 1000 * 60);
}
timeout(); // start
Post a Comment for "Help Chosing Between Settimeout And Setinterval"