user3422501
user3422501

Reputation: 145

Parallel execution of functions in javascript

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.

Upvotes: 3

Views: 18317

Answers (1)

ffflabs
ffflabs

Reputation: 17481

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.

Upvotes: 4

Related Questions