Question

Given the fact that Javascript is a single-threaded language, what would be the sequence of execution in the following code in ExtJs?

FuncA();

Ext.Ajax.request({
    url: 'ajax.php',
    params: {
        id: 1
    },
    success: function(response){

        FuncB();
    }
});

FuncC();

FuncD();

Here would the sequence of execution of functions be A-C-D-B?

Or

Is it ever possible that FuncB() gets called prior to FuncC() or FuncD()? If yes, then in which conditions?

Thanks in advance for any help.

Was it helpful?

Solution

The order will always be A-C-D-B unless the ajax request is synchronous, but it's not really recommended to use that since it causes the UI to hang.

For example, try this (in Chrome, preferably)

function f1() {
    var s = '';
    for (var i = 0; i < 10000000; ++i) {
        s += 'a';
    }
}

function f2() {
    var s = '';
    for (var i = 0; i < 10000000; ++i) {
        s += 'b';
    }
}

Ext.require('Ext.Ajax');

Ext.onReady(function() {

    var d;
    Ext.Ajax.request({
        url: 'data.json',
        success: function(){
            console.log('finished');
        }
    });

    d = new Date();
    f1();
    console.log(new Date() - d, 'f1 done');
    d = new Date();
    f2();
    console.log(new Date() - d, 'f2 done');

});

You will see that even though it takes around 1s to run the code, the ajax request always fires last, even though the request itself only takes around 7ms (it's a local box). Then try it again by commenting out the calls to f1/f2.

OTHER TIPS

A {B} C {B} D {B}
b can execute at all the positions marked {b}. but will be executed only once.
edit:-
no javascript isnt a multi threaded language. so maintains a queue of the code to be executed. so when it reaches funcC it starts executing FuncC and then after ii returns looks for next function to be executed in the queue which might be funcB(if the ajax request is completed) so funcB can only be executed in between 2 functions calls

Please note that the javascript code runs top to bottom. So in this case, your code execution will start at funcA() and ends at funcD() but funcB() can be called anytime because it totally depends upon how soon ajax.php returns the response.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top