1

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

5
  • 1
    In Simple Words callback is a function called after finishing some task by given function. So Nah! not all of them are callback. Commented Jun 2, 2014 at 7:13
  • 1
    hide is an asynchronous function that takes a callback. Look up those terms. Commented Jun 2, 2014 at 7:14
  • I have no confusion about what callback does. My question is what if in a function two statements are provided such as alert(complex calculation); and on the next line it has alert('hey'); I know without a doubt that first alert gets executed first because it appears first in the code. BUT is it not possible that alert('hey') which appears second might get executed even before alert(complex calculation) has finished? Do i need callback there to ensure that 'hey' appears on screen only after complex calculation has been performed Commented Jun 2, 2014 at 7:20
  • 1
    +1 Nice Question. After a long time A question that made me think. Commented Jun 2, 2014 at 7:36
  • @VedantTerkar well thank you. Some misunderstood the question as What is callback? Thank you for your answer it helped. Commented Jun 2, 2014 at 7:38

4 Answers 4

2

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.

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

2 Comments

are you sure about Ajax, setTimeout and setInterval and thrid party library? Is there anything else that can be asynchronous? any other method etc
I'm sure there are other things. CSS transform operations, web sockets calls, etc... I meant only that those are the common ones. Sorry!
1

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.

4 Comments

I understand that but take a look at last example i gave the one which appends something a table. Is it not possible that alert('hey') might appear on screen even when append is in process?
@Arbaaz no. The for loop in fn1 will complete execution before the alert() in fn2 is fired.
so basically as @gwcoffey said I should be worried about that unless I am doing Ajax, setTimeout and setInterval, or using a third party library right?
@Arbaaz you should read up about how asynchronous JavaScript with callbacks work. As long as you test your application you should be fine.
0

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.

Comments

0

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. ;)

Comments

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.