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?

5
  • 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 Commented Jan 14, 2016 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. Commented Jan 14, 2016 at 11:00
  • @Victor may I ask how can I use setTimeout for this example? May give me a fiddle link? tnx Commented Jan 14, 2016 at 12:44
  • 1
    @chalist JSFiddle: jsfiddle.net/63sqr0gc/3 though the whole idea is already described e.g. in stackoverflow.com/a/672784/1235394 Commented Jan 14, 2016 at 13:26
  • @Victor awesome. thanks dude :) Commented Jan 14, 2016 at 14:03

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.