Hello whatever,
today I've read a very nice article about browsers' JS main loop and Web Workers [*] and it seems that Web Workers is exactly what you need. Like you said, JS is a single-thread, but Web Workers "break this rule": they are processed in separate threads and hence don't hang the interface. Still, they have their limitations: DOM can't be manipulated from a Web Worker. Hence, you should create a Web Worker and set an event handler: once the job is done by your Web Worker, you can change DOM. Normally WW are used with JS in a separate file, but this can be worked around using stuff like
var worker = new Worker(
window.URL.createObjectURL(
new BlobBuilder().append(
"onmessage = function(e) { postMessage('hello habrahabr'); }"
).getBlob()
)
);
worker.postMessage();Another option is to use setTimeout instead of WW: in this trick JS bits (small enough) are executed between other stuff in the event loop and hence the interface doesn't hang [**].
Best regards,
Yakov.
[*] it's in Russian so probably not useful for you:
https://habrahabr.ru/company/tradingview/blog/178261/[**] see the first answer here:
https://stackoverflow.com/questions/714942/how-to-stop-intense-javascript-loop-from-freezing-the-browserвторник, 11 июля 2017 г., 21:59:02 UTC+3 пользователь whatever написал: