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,
The first parameter to
setInterval, which when simplified looks like this: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 theindexvariable defined in the outer function.setIntervalexpects 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, thenall.eq(index).hide();will be executed – I assume this hides the element that matches the current index.indexis then incremented, with the second if setting it back to 0 if it reaches the maximum number of elements inall, 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.