Javascript - Why does this function loop twice?
Trying to solve that problem, but no luck for hours...
I have
var screen1 = $('#screen');
var screen2 = $('#screen_teams');
var screen3 = $('#field_position');
. . .
screenFade(screen1,1000,1);
function screenFade(screen,delay,next) {
if (next == 1) {
screen.delay(delay).fadeOut(1000, function() {animation(2);console.log('2');});
} else {
screen.fadeIn(1000).delay(delay).fadeOut(1000, function() {animation(next);console.log(next);});
}
}
function animation(seq) {
if (seq == 2) {
screenFade(screen2,2000,3);
};
if (seq == 3) {
screenFade(screen3,2000,4);
};
if (seq == 4) {
screenFade(screen4,2000,5);
};
}
And firebug outputs: 2 2 3 3 4 4 5 5
Do you know the solution? Tha开发者_高级运维nks in advance!
I think your biggest issue is the recursive nature of your code... I think a little simplification is in order.
If you put all of your "screens" as child elements of a parent then you can easily use a rotate plugin I wrote for jQuery:
If the parent element had an ID of screens
and each screen was a child div
then you could use the plugin like this:
function() rotateCallback(screenNumber, screen) {
if(screenNumber == 4)
callOtherFunction();
}
$(function() {
$("#screens div").Rotate({ cycleTime: 2000, fadeTime: 1000, callback: rotateCallback});
})
On the window load event this will select all of the child divs of the parent with an ID of screens
and then rotate every 2 seconds fading over 1 second.
Here's the plugin code:
jQuery.fn.Rotate = function(config) {
var currentIdx = 0;
var items = [];
var itemCount = this.each(function(idx, item) {
items.push($(item));
}).length;
function rotateItem()
{
var front = items[currentIdx];
var back = items[currentIdx = ((currentIdx + 1) % itemCount)];
back.fadeIn(config.fadeTime);
front.fadeOut(config.fadeTime, function() { front.hide() });
if(config.callback)
config.callback(currentIdx, back);
}
setInterval(rotateItem, config.cycleTime);
}
--Update--
Added callback on rotation and example.
精彩评论