3

I listened that javascript is single threaded am I right? Then how can I implement execution of functions(multiple) in parallel(simultaneous).

I have script as shown below, and I want to tell you that each xml file size is 4.6MB.

myfunction('sample1.xml');
myfunction('sample2.xml');
myfunction('sample3.xml');
    .
    .
myfunction('sample15.xml');

function myfunction(name) {

    $.ajax({
        type: "GET",
        url: name,
        dataType: "xml",
        success: parseXml
    });

    function parseXml(xml) {

        //searching the xml file 


    }

}

My aim is to speed up the process of searching xml file, for that I have thought that parallel execution is good. So is it possible to have parallel execution in javascript functions or is their any way to speed up my functions execution.

5
  • 2
    The JavaScript isn't simultaneous (parallel). The requests are sent one by one, but the browser can handle multiple http requests at once. The JavaScript is simply inactive while the browser processes the requests and waits for the responses. When each response returns, the JavaScript callback is invoked. Commented May 29, 2014 at 17:28
  • what you can do its demand your multithread job to a server side script(c# for example) Commented May 29, 2014 at 17:29
  • 1
    You can delegate those functions to a web worker (html5rocks.com/en/tutorials/workers/basics), this is the only way right know to create multiple proccesing contexts in JavaScript. Don't worry about threads while working with JavaScript, it works with an event-flow loop, and how it is exactly executed depends on the implementation, you should not worry about threading in JavaScript as you have no way to control how it is done. The only tool you've got to increase performance is the code itself, the alghoritms you use. Commented May 29, 2014 at 17:31
  • 2
    @cookiemonster - I would change "JavaScript is simply inactive" to "JavaScript is idle and can do something else while waits for the responses". Commented May 29, 2014 at 17:37
  • @Igor: You're right, that's better. Makes it clear that the JS isn't "paused" in any way. Commented May 29, 2014 at 17:37

1 Answer 1

4

You can trigger as many ajax request as you want and they will fire in parallel because they are asynchronous by default. The problem is that your browser will execute parseXML whenever the ajax request is ready, so you might end freezing your browser anyway.

You can defer the execution of parseXML with Mark Gabriel's response

setTimeout(function(){ parseXML(xml) }, 0)

Which would prevent browser freezing, but in the end would execute parseXML sequentially.

Depending on what exactly are you trying to do inside parseXML, it might be better to use webworkers to execute the XML parsing in a parallel browser process. This way you will be opening a background process to perform a specific task. You create the worker and send the filename as a message, then wait for the worker to return whatever you are expecting from parseXML

var worker = new Worker('/js/parseXML.js');
worker.addEventListener('message', function (e) {
        console.log('Webworker answer is',e);
    }, false);

worker.postMessage('sample1.xml'); // Send data to our worker.

the contents of parseXML.js would be

importScripts("/js/jquery.js");

self.addEventListener('message', function (e) {
    console.log('Webworker received', e.data);
    $.ajax({
        type: "GET",
        url: e.data,
        dataType: "xml",
        success: parseXml
    });

    function parseXml(xml) {
        //searching the xml file 
        self.postMessage(parsedXML);
    };
}, false);

Please keep in mind that this logic only makes sense if you are planning to get a string, array or hash as the return of parseXML. You can't operate on global objects of the main script inside a webworker nor return complex objects.

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

4 Comments

Your solution using the worker is correct, however the requests will not be fired in parallel as JavaScript is single threaded. Launching a multitude of AJAX requests will happen sequentially and they will be handled sequentially regardless whether you'd be using a timeout or not.
It depends. Parsing m request with one webworker (m*1) is different than parsing 1 each with m webworkers (1*m). In this case I'd go for creating n webworkers and have each parse m/n requests (n*m/n). I made a POC for the (1*m) case in the following link: bl.ocks.org/amenadiel/4d4c3cba4c47f8a44ba0
I was referring to your opening statement You can trigger as many ajax request as you want and they will fire in parallel because they are asynchronous by default, They won't be executed in parallel from JS's point of view
Oh, regarding that, the firing is inmediate. The resolving is enqueued tho.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.