Javascript order in which the function is called

Hi, I'm still pretty new to programming, and I have not had the opportunity to fully understand Java or Javascript only in those programming languages ​​that I know, but I really try to understand Javascript.

What I came across is that several times I do not understand when javascript calls my created functions, for example. I created a small jQuery plugin: http://jsfiddle.net/a9gjK/1/

The plugin is very simple, images are set on top of each other using an absolute position. Then I take the first image and set the z-index to 100, then take the next image and set its z-index to 50 after that. I take the first image again and reduce it to 0 opacity, then I call the callback function witch sets the first z-index of the image to 0 and reduces it to 1 opacity, and the next z-index of the image is 100.

After completing this process, the first hole is first installed on the next element. This is where my problem appears. If I first set the variable to the next img inside the callback function, the plugin will work fine and everything will be fine, but if I do it outside the callback function after the script is executed once on each image and should start again with The first image, when it disappears, I see the background. This does not happen if I set the first image to a callback function.

Can someone explain why this is happening, and on what topic it is related, so that I can better read and understand what is happening.

+4
source share
1 answer

You experience behavior caused by asynchronous functions .

JQuery animation functions, such as fadeTo , execute asynchronously, which means that the function can end anytime after it is called. If you call two asynchronous functions in order,

 asynch1(); asynch2(); 

code behavior may change because there is no guarantee that asynch1 will run before asynch2 .

This requires callbacks. You can pass a function that will be run after the asynchronous function completes.

When you do it

 $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 $next css will be installed after the fade animation is complete.

+4
source

Source: https://habr.com/ru/post/1402897/


All Articles