I have开发者_运维百科 an ad slide-show on my homepage. It consists of 2 images.
I preload these 2 images, making new Image()
and setting .src
to them.
I have a function giveNextName
that return name of the next image (that should be in src
attribute of the img
element) (I do this, because soon, slideshow will consist of more than 2 images)
So the main code looks like:
BillBoard = {};
BillBoard.folder = "/pictures/cards/";
BillBoard.ext = "png";
BillBoard.$ = $("#billboard img");
BillBoard.pics = 2;
BillBoard.changeTime = 7000;
BillBoard.names = ["ad1","ad2"];
BillBoard.currentState = 0;
BillBoard.images = // array of preloaded Images
(function(){
var image, images = [];
for (var i=0; i<BillBoard.pics; i++) {
image = new Image ();
image.src = BillBoard.folder+BillBoard.names[i]+'.'+BillBoard.ext;
images.push (image);
}
return images;
}());
BillBoard.giveNextName = function(){/* getting the next name */};
// BillBoard change action
BillBoard.change = function(){
BillBoard.$.fadeOut(function(){
$(this).attr('src', BillBoard.giveNextName());
$(this).fadeIn();
});
}
// Starting BillBoard
window.setInterval(BillBoard.change, BillBoard.changeTime);
So, idea is simple. with window.setInterval
I call BillBoard.change
every n seconds. But, I don't know why, billboard becomes changing faster and faster, until there will be no picture at all (fadeIn doesn't have time to execute)
Where is my mistake?
UPD. Thanks to Yann Ramin for the link.
I shouldn't call BillBoard.change
every n seconds via window.setInterval
. Instead, I should add call of BillBoard.change
in the callback of fadeOut()
.
I mean this code:
BillBoard.change = function(){
BillBoard.$.fadeOut(function(){
$(this).attr('src', BillBoard.giveNextName());
$(this).fadeIn();
window.setTimeout(BillBoard.change, BillBoard.changeTime);
});
}
// simply call the change function
// it will be calling itself every n seconds
BillBoard.start = (function(){
window.setTimeout(BillBoard.change, BillBoard.changeTime);
}());
See this for a likely culprit:
http://www.ozonesolutions.com/programming/2011/07/jquery-fadein-window-setinterval-a-bad-combination/
精彩评论