Suppose I have setInterval(PostToServer, 1000);
. PostToServer
function makes ajax post, which may take longer than a second. So what happens then: a second call is made while the first hasn't finished or the end of call is awaited before making new one?
In case of time intensive synchronous operations, setTimeInterval may break the rhythm. Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it.
In the above program, the setInterval() method calls the greet() function every 1000 milliseconds(1 second). Hence the program displays the text Hello world once every 1 second. Note: The setInterval() method is useful when you want to repeat a block of code multiple times.
The real-time interval can only be greater than or equal to the value we passed. From the above code, we can see that setInterval is always inaccurate. If time-consuming tasks are added to the code, the difference will become larger and larger ( setTimeout is the same).
This is unlikely to make much of a difference though, and as has been mentioned, using setInterval with long intervals (a second is big, 4ms is small) is unlikely to have any major effects.
Javascript is single threaded (except for HTML5 web workers which are not involved in this issue) with an event queue. A subsequent call from setInterval()
will never start until the previous call is done. Only one can ever be active at a time.
When the time for your interval occurs, internal to the JS engine the timer fires and an event is added to the javascript event queue. When the currently running JS thread of execution finishes (and not before), the JS engine goes and fetches the next event from the event queue and starts that thread of JS execution. Thus two executing paths in JS will never overlap or be going on at the same time. So, two function calls from setInterval() will never overlap. The second one won't start until the first one is done executing.
But, relative to your question, what this means is that two intervals from setInterval()
will never overlap, but if you're making an asynchronous ajax call on the first interval timer and the starting of the ajax call finishes right away, and the second interval fires before the first asynchronous ajax call has fired it's completion function, then your ajax calls will or can overlap.
If you wanted to prevent more than one ajax call being in flight at a time, you would have to write some code to specifically prevent that either by not firing the second ajax call until the previous one was completed or by just skipping any ajax call if the previous one is still going.
See this post for more info on the JS event queue and how it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With