I know that the setInterval function is pretty much single threaded. But if we set the time to a very small value like 50 milliseconds:
setInterval(function()
{
// do really heavy stuff
}, 50);
then the first generated event might not finish in time then I guess a second event is put into the browser’s queue and then third, fourth etc. So basically this means that the browser’s queue is getting bigger really fast and it’s clearly not a good thing( is it? )
So far I’ve come with these two solutions:
1) Wait for the first event to finish and then call a second one(by using timeout):
var func = function()
{
setTimeout(function()
{
// do really heavy stuff and when it's finished call again
func();
}, 50)
}
2) Create a flag that monitors the event’s state:
var isIntervalInProcess = false;
setInterval(function()
{
if ( isIntervalInProcess )
return false;
isIntervalInProcess = true;
// do really heavy stuff
isIntervalInProcess = false;
}, 50);
Are those best practices for getting rid of events overlaping?
The first example you provided is a common technique used to avoid the pitfalls of
setInterval. As far as “best practice” is concerned, you should choose the right technique for the right situation (yes, that’s unfortunately quite vague).It’s common to use brief intervals for short periods of time using
setIntervalfor animation. In these cases, the callback should be streamlined for performance and easily cancelled. jQuery uses a delay of 15ms, and it works great.For longer-running functions, it’s probably better to break them down into a queue of asynchronous functions. Queuing the same function over and over is identical to your first
setTimeoutexample.Your second example has the issue that items in the callback queue will never execute out of order. The second queued function will only be called after the first function has executed, at which point 2 or 3 more functions may be queued.
There is, however a
cached pollingtechnique that would allow the main body of the callback to execute only when a state change has occurred: