-1

I am learning jQuery, and am trying to understand how the callback works. I know what it does (calls some function after finishing with the first one), but it's the syntax that thrown me off a bit. I have this code:

showMenuElement( 0 ); // call to initiate the menu

function showMenuElement( x ) {
    x += 1; // cycling through elements
    if (x < 4) {
        var el = "#menu-" + x;
        $( el ).fadeIn( 1000, showMenuElement(x) ); // show one element, then show next in line
    }
}

...and it doesn't work like I want it to, as it shows all the menu items at once! (here's the working fiddle: fiddle 1)

However, if I add the function() {...} part, like this:

showMenuElement( 0 ); // call to initiate the menu

function showMenuElement( x ) {
    x += 1; // cycling through elements
    if (x < 4) {
        var el = "#menu-" + x;
        $( el ).fadeIn( 1000, function() { showMenuElement(x) } ); // show one element, then show next in line
    }
}

then it works like a charm, showing one item after another (as per fiddle 2).

I am looking for the explanation for why it does behave this way? I though, that since it's a callback, it will look for a name of a function to implement, so what does the writing function() {...} explicitly changes?

senemedar
  • 3
  • 4

2 Answers2

1

In your first code snippet, in the fadeIn method you call your function showMenuElement, instead of doing this fadeIn need a callback reference, not a call of a callback, it's because your second snippet work, you give it a reference without calling it.

(pardon my bad english)

Christophe
  • 408
  • 2
  • 10
  • Well, I though it was the idea of calling it, but that the call itself will be executed after the animation finishes. Apparently I had it wrong :) – senemedar Nov 17 '17 at 10:05
  • When you want to deal with parameter for a callback function, you've many solutions, yours with the function() { showMenuElement(x) } is a good solution, keep going with it. :) – Christophe Nov 17 '17 at 10:09
  • @ChristopheCoquelet: Your on the good way, but maybe you can improuve a little bit your answer by explaining technically why the first method doesn't work. – Techniv Nov 17 '17 at 10:11
  • @Techniv thanks for your recommandation, i'll try to apply your advice for my future answer :) – Christophe Nov 17 '17 at 11:02
  • @ChristopheCoquelet Thank you for the kind words :) I'm still learning, so it's nice to have a feedback like that! – senemedar Nov 17 '17 at 14:40
0

First method won't work as you are expecting. Because you are executing the function and passing the return value of 'showMenuElement' as callback.

But in second case you passing anonymous function as callback.Here it works.

Remove () from the method i.e write the line as

$( el ).fadeIn( 1000, showMenuElement );

Then callback works.

But you have to deal with the x parameter in different way.

Pradeep
  • 140
  • 9