Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use setInterval to call functions asynchronously?

The following code is taken from Project Silk (a Microsoft sample application) The publish method below loops thru an an array of event callBacks and executes each one. Instead of using a for loop setInterval is used instead.

The documentation says this allows each subscriber callback to be invoked before the previous callback finishes. Is this correct? I thought the browser would not allow the execution of the function inside the interval to run until all prior executions of it had finished.

Is this really any different than doing a for loop?

that.publish = function (eventName, data) 
{
    var context, intervalId, idx = 0;
    if (queue[eventName]) 
    {
        intervalId = setInterval(function () 
        {
            if (queue[eventName][idx]) 
            {
                context = queue[eventName][idx].context || this;
                queue[eventName][idx].callback.call(context, data);
                idx += 1;
            } 
            else { clearInterval(intervalId); }
        }, 0);
    }
like image 761
C.J. Avatar asked Feb 21 '23 11:02

C.J.


1 Answers

Using setInterval here does make the execution sort of "asynchronous", because it schedules the execution of the callback for the next time the main execution thread is available.

This means that the callback executions should not block the browser because any other synchronous processing will take place before the callbacks (because the callbacks are scheduled to run only when the main execution thread has a spare millisecond) - and that's what makes this construct "better" than a regular for loop - the fact that the callbacks won't block the browser and cause the dreaded "This page has a script that's taking too long" error.

The side effect of this scheduling pattern is that the timeout is only a "suggestion" - which is why they use 0 here.

See: http://ejohn.org/blog/how-javascript-timers-work/

like image 162
mWillis Avatar answered Feb 24 '23 02:02

mWillis