SamuraiJack
SamuraiJack

Reputation: 5539

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??

Upvotes: 1

Views: 1111

Answers (4)

Vedant Terkar
Vedant Terkar

Reputation: 4682

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.

Upvotes: 0

Amin Jafari
Amin Jafari

Reputation: 7207

no it is not possible, for functions the JavaScript does them line by line but all in once, BUT it returns the result of the first one after giving the result of the second one! but as for the other example, it is obvious that hide() is going to take much longer to give the requested respond comparing to alert which is a browser built in function and that's why the alert appears to be working before hide(), I don't know the exact time that it takes to do these things but if you google it, you can learn them too if you need to!

BTW when an alert() pops up, it shuts down the whole javascript codes while it's on, just for you to know. ;)

Upvotes: 0

gwcoffey
gwcoffey

Reputation: 5921

To answer your question: No.

The key is that certain javascript functions are asynchronous. These really only come in two common categories:

  1. XmlHttpRequest (i.e. AJAX) calls, where the browser goes out to the network to get something, and it lets the script continue running while it gathers the response.
  2. timeouts and intervals, where you tell the browser to call some code after a delay. The script will continue unimpeded and then, when the time arises, the timeout code will run.

In your examples:

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

The hide function in jQuery is timeout based. So your script does not have to wait for the animation to complete before it gets on with its business. jQuery provides a callback parameter so you can choose to have something happen after the animation completes if you want.

So in this example:

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

It is wrong to say the alert "might" execute before the hide finishes. Unless your code is executing so slowly that it takes more than 1 full second for an alert to show, it will execute before the hide completes. 1000ms is an eternity to a line of javascript.

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

In this example, there is nothing asynchronous about the code. alert is a so called blocking call, meaning nothing happens in the script until you dismiss the alert. So you are guaranteed that the alerts will appear in order no mater how complex you make the parameter.

In fact, the complexity of the parameter has no bearing because it will evaluate in full before the resulting string is passed to the alert function.

So long story short, unless you're doing Ajax, setTimeout and setInterval, or using a third party library (which should document its behavior) your code will execute in order.

Upvotes: 2

James Donnelly
James Donnelly

Reputation: 128791

No. The reason the alert() occurs first in example 2 is because the hide() call is asynchronous. The hide() function is fired, but this has a 1000 millisecond delay. The alert() is fired instantly afterwards, not 1000 milliseconds afterwards, therefore it appears that the alert() was fired first.

In example 1 the alert() fires only when the hide() has completed, as this uses a callback function.

Upvotes: 1

Related Questions