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.