1

I have two script.

First:

a = 0;
for (var i = 1000000000 - 1; i >= 0; i--) {
    a += i;
};
console.log(a);

Secend:

setInterval(function(){
    if (l.data('pos') == 0) {
        l.css('margin-left', '10px');
        l.data('pos', '1');
    }else{
        l.css('margin-left', '0');
        l.data('pos', '0');
    }
}, 100);

JSFiddle demo

As you see, browser run second section after finishing first section.

Can I run first section in background and second section runs from document ready?

Oxi
  • 2,918
  • 17
  • 28
Chalist
  • 3,160
  • 5
  • 39
  • 68
  • 1
    Javascript is single threaded language, meaning only running in one thread. But if your first section isn't requestiong/updating DOM, you could use on modern browser [webworkers](https://www.w3.org/TR/workers/) – A. Wolff Jan 14 '16 at 10:39
  • 1
    If web workers are not an option, then you could split computation in first script into small chunks with help of `setInterval`/`setTimeout`. Then it won't block UI and other scripts from execution. – Victor Jan 14 '16 at 11:00
  • @Victor may I ask how can I use `setTimeout` for this example? May give me a fiddle link? tnx – Chalist Jan 14 '16 at 12:44
  • 1
    @chalist JSFiddle: https://jsfiddle.net/63sqr0gc/3/ though the whole idea is already described e.g. in http://stackoverflow.com/a/672784/1235394 – Victor Jan 14 '16 at 13:26
  • @Victor awesome. thanks dude :) – Chalist Jan 14 '16 at 14:03

1 Answers1

3

JavaScript is single threaded, however HTML5 Web Workers supports multithreading but you need to handle supporting old browsers.

More info: https://msdn.microsoft.com/en-us/hh549259.aspx

mylee
  • 1,293
  • 1
  • 9
  • 14