Reputation: 583
If I use the setInterval function to call an asynchronous JavaScript function each X seconds will the interval wait X seconds after the previous execution is finished or X seconds after the previous execution is called? E.g. if I display a timeline of the calls is it:
0 sec : setInterval(funcX, 10000)
10 sec : funcX - takes 3 seconds to execute
20 sec : funcX
or
0 sec : setInterval(funcX, 10000)
10 sec : funcX - takes 3 seconds to execute
23 sec : funcX
Upvotes: 0
Views: 267
Reputation: 191829
If the function actually takes 3 seconds to execute, you have serious problems.
This is not particularly relevant to you because you are using Ajax, and the actual Ajax call should be practically instantaneous.
If you want the Ajax call to complete before the interval continues again, setInterval
is undesirable. Use setTimeout
instead.
function atTime() {
ajax().done(function () { setTimeout(atTime, 10000); });
}
atTime();
Upvotes: 0
Reputation: 103428
Taken from Mozilla documentation:
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
Therefore it's every X seconds. But if the function takes longer than X seconds to execute, then the thread will be locked and will execute when it's free.
For more information on JavaScript timings I recommend John Resig's article How JavaScript Timers Work.
If you wish for it to be X seconds after the function has executed, use setTimeout()
and call this at the end of your function:
runFunc();
function runFunc(){
//code here....
setTimeout(runFunc, 3000);
}
This will cause infinite recursion, emulating setInterval()
, but only starting the X second delay once the current function has finished executing.
Upvotes: 2