Can you use setInterval to call functions asynchronously?

The following code is taken from Project Silk (a sample Microsoft application). The publishing method below goes through an array of event calls and makes each one. Instead of using a for loop, setInterval is used.

The documentation says that this allows you to activate the callback of each subscriber until the previous callback is completed. It's right? I thought that the browser would not allow the execution of the function inside the interval until all its previous executions were over.

Is this really 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); } 
+4
source share
2 answers

Using setInterval here makes the execution "asynchronous" because it schedules the execution of the callback the next time the main thread of execution is available.

This means that the callback should not block the browser, because any other synchronous processing will be performed before the callbacks (since the scheduled calls will only be executed when the main thread of execution has a spare millisecond), and that this creates a โ€œbetterโ€, than a regular loop is the fact that callbacks will not block the browser and cause the scary "This page has a script error that takes too long."

A side effect of this scheduling pattern is that the timeout is just a โ€œsuggestion," so they use 0 here.

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

+4
source

setInterval(..., 0) can be used to provide control over the browser user interface to prevent it from freezing if your code takes a long time.

In this case, that.publish will exit almost immediately before executing any callback. Then each callback will be launched "in the background" - they will be placed in the event loop, and each of them will allow the browser to do this before the next callback is made.

This seems like a good idea when handling events, because you do not want event processing to block the browser, even if there are many, or some of them take a lot of time.

About documentation - as indicated, incorrect. Javascript is single threaded. But if you called publish() several times in a row, it is true that all calls will be completed before any callbacks are made, due to setTimeout . Perhaps this is what the documentation means?

+4
source

Source: https://habr.com/ru/post/1396971/


All Articles