user1146440
user1146440

Reputation: 363

Javascript order on which functions are being called

Hi I am still pretty new to programming and I haven't had the chance to fully understand Java or Javascript the only programming languages I know but I am trying really hard to understand Javascript.

What I am facing is that some times I do not understand when javascript is calling my created functions for example. I have created a small plugin for jQuery: http://jsfiddle.net/a9gjK/1/

The plugin is very easy the images are set on top of each other using position absolute. I then take the first image and set the z-index to 100 then I take the next image and set it's z-index to 50 after this I take the first image again and fade it to 0 opacity, then I call a callback function witch sets the first image's z-index to 0 and fade it to 1 opacity and the next image's z-index to 100.

After this hole process is done the variable first is set to the next element.This is where my problem appears. If I set the variable first to the next img inside the callback function the plugin works well and everything is well, but if I do this outside the callback function after the script is ran once on each image and has to start again from the first image when it fade's out I see the background. This doesn't happen if I set the first image to next inside the callback function.

Can anyone explain why this is happening and on what topic is this related so I can read and understand better what's happening.

Upvotes: 4

Views: 106

Answers (1)

Peter Olson
Peter Olson

Reputation: 142911

You are experiencing behavior caused by asynchronous functions.

jQuery animations functions like fadeTo execute asynchronously, which means that the function can complete any time after you call it. If you call two asynchronous functions in order,

asynch1();
asynch2();

the behavior of the code can vary because there is no guarantee that asynch1 will execute before asynch2.

This is what callbacks are for. You can pass a function in that will run after the asynchronous function is completed.

When you do this,

$first.css({
    'z-index': 0
}).fadeTo(50, 1);
$next.css({
    'z-index': 100
});
$first = $next;

there is no way to predict what will happen first.

If you use a callback instead

$first.css({
  'z-index': 0
}).fadeTo(50, 1, function() {
  $next.css({
    'z-index': 100
  });
  $first = $next;
});

you know that that the $next css will be set after the fade animation is done.

Upvotes: 4

Related Questions