0
setInterval((function() {
        var index = -1;
        return function() {
            var all = $('#latest a');
            if (index >= 0) {
                all.eq(index).hide();
            }

            index++;
            if (index == all.length) {
                index = 0;
            }

            all.eq(index).show();        
        };
    })(), 1000);

how the code is executed? when index = -1; it not fits the first if condition, then the code goes to execute index++; now the index=0, then which step the code will be executed? if (index >= 0) or if (index == all.length) why?

i can't follow the first parameter of the setInterval well. could you explain it with more datails. thank you,

runeveryday
  • 2,751
  • 4
  • 30
  • 44

3 Answers3

2

SetInterval call the function in the first parameter every second.

I will split you code into a semantically equivalent one to be more clear

timedFn = (function() {
    var index = -1;
    return function() {
        var all = $('#latest a');
        if (index >= 0) {
            all.eq(index).hide();
        }

        index++;
        if (index == all.length) {
            index = 0;
        }

        all.eq(index).show();        
    };
})();

setInterval(timedFn, 1000);

timeFn is a closure and then the index variable value is retained between the different calls.

At the first call, index is -1, and then the execution skip the first if and the control go to the index++ instruction (likely the '#latest a` link are all hidden at the first run so you don't have to hide anything)

Now, a digression before we can continue: You should know that eq method is applied to a collection of elements and retrieve the zero based nth element of the collection it is applied to. If you have a collection of three elements you can address them by eq(0)..eq(2) and this is why you step into this >strange if. it is a guard that means if you pass over the last element of my collection >the restart from the first one.

The updated index now contains 0 and, if the collection is empty you will have a bug as the index remains unchanged (index=0 but index is already zero) and the show will attempt to display a non existent element.

By the last instruction the first link is displayed and the execution stops.

After a second the function is called a second time but this time the index star at 0, not -1 and then the execution is repeated:

  • hide the first element
  • add 1 to index
  • if there is just an anchor in your set then reset the index to zero
  • show the second elements
  • the function ends

After another seconds the function is called again but you should already know how it works.

You can google on closures to have an indeep view of their inner working or just refer, as a starting point, to How do JavaScript closures work? on Stackoverflow itself.

Community
  • 1
  • 1
Eineki
  • 14,773
  • 6
  • 50
  • 59
  • +1, for an awesome answer. But in my opinion the self executing function that returns a function, is possibly the big question. But I've been drinking so I really cant tell – Joe Oct 27 '11 at 01:52
1

The first parameter to setInterval, which when simplified looks like this:

(function() {
   var index = -1;
   return function() {
      // some code that can access index
   };
})()

defines an anonymous function expression that is immediatedly executed (note that at the end of the function definition it has () causing the execution). When this outer function is executed it returns the inner anonymous function, where due to the magic of closures the inner (nested) function has access to the index variable defined in the outer function.

setInterval expects a function expresssion/reference as its first parameter, which means it is happy if the above structure is passed in as the first parameter since the above returns a function.

The point of all that is essentially to keep the functionality self-contained, rather than declaring a "plain" function that uses a global variable called "index".

As for what the code within the function actually does, well, it will be executed every 1000ms. If index >= 0, which it will be every time except the first time, then all.eq(index).hide(); will be executed - I assume this hides the element that matches the current index. index is then incremented, with the second if setting it back to 0 if it reaches the maximum number of elements in all, essentially ensuring that the code will keep cycling through the elements. Finally the element at the (newly incremented) index is shown.

Presumably all of these elements are hidden to begin with such that the overall effect is to show and then hide one element at a time, changing once per second.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

If index=0, then the all.eq(index).hide() will be executed. The second if could also be executed, but only if all.length = 0.

NickLH
  • 2,643
  • 17
  • 28