Arbaaz Arbaaz - 1 month ago 6
Javascript Question

What will be the sequence of execution of this javascript/Jquery code?

Ok, I am pretty new to jquery and Javascript.
I was reading about callback on w3school and it gives two examples.

Example1:

$("button").click(function(){
$("p").hide("slow",function(){
alert("The paragraph is now hidden");
});
});


Example2:

$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});


I understand that in first case alert will ONLY be executed after hide() function has finished.
However in second example it is possible that alert might execute before hide finishes.
This has caused some confusion in my understanding. Like for example is it possible that
alert('hey')
might get executed before alert which comes before it (one with mathmatical calculation) in following case..

$("button").click(function(){
alert(1+2+(3*4)..blah..blah);
alert('hey');
});


OR
in this case..

$("button").click(function(){
fn1();
fn2();
});

function fn1(){
for(var i=0;i<100;i++){
$('table').append(blah);
}
}
function fn2(){
alert('hey');
}


Is it possible that 'hey' might appear before fn1 has finished appending?
If so do I need to write every thing as callback??

Answer

When using alert or confirm in Javascript, the browser is forced into a synchronous (existing or occurring at the same time) process where everything (even the loading of another page) halts until the user dismisses the dialog.

So when you alert something, browser will halt execution of other functions.

But jQuery hide and other animation functions are asynchronous (not existing at the same time) so that browser will go to next line without waiting for them.

For ex.

$(document).ready(function(){
  fn1();
  fn2();
});

function fn1(){
    for(var i=0;i<100;i++){
 $('body').append("<div>blah</div>");
        console.log("blah!");
        }
}
function fn2(){
console.log("Hey!");
}

Here hey will be logged after blah (100 times) as the browser waits for f1() to complete.


DEMO
But if you try something like:

$(document).ready(function(){
  fn1();
  fn2();
});

function fn1(){
    for(var i=0;i<100;i++){
if(i%10==0)
{
fn2();
    alert(true);
}
        console.log("blah!");
        }
}
function fn2(){
console.log("Hey!");
}

Then alert will show its way of working.

Also in jQuery:

$("p").hide("slow",function(){
    // This is the call back function and not others.
  });

The callback will be executed when any async or sync function first of all executes its tasks.