我寫我的網站jQuery插件,這裏是一個片段:定時器越來越快
(function($){
var options;
var fqTimer;
var counter = 1;
$.fn.jsSlideShow = function(settings){
options = $.extend({
frequency: 3000,
speed: "slow",
images: [],
position: "center center"
}, settings);
addImages();
doFade();
return this;
};
function doFade(){
fqTimer = setTimeout(function(){
fade();
}, options.frequency);
}
// other functions
});
它的工作原理,但我有一個問題。我有這樣的代碼在jQuery的阿賈克斯成功回調:
$("#player").jsSlideShow({
images: imgs
});
但會發生什麼,就是現在我的doFade()
函數被調用更快,我的每一個成功的AJAX調用doFade()
時間變得更快。有沒有辦法阻止這種情況發生?
這裏是我的Ajax調用:
success: function(data){
var player = $("<div>").attr("id", "player").addClass("jsSlideShow");
$("#page").html(player);
var imgs = new Array();
for(i in data){
file = data[i]["filename"] + ".jpg";
imgs.push("/media/gallery/" + file);
}
$("#player").jsSlideShow({
images: imgs
});
}
編輯:工作副本的新
以下是完整的插件:
(function($){
$.fn.jsSlideShow = function(settings){
var options;
var fqTimer = null;
clearTimeout(fqTimer);
var counter = 1;
var jsSlider = $(this);
options = $.extend({
frequency: 3000,
speed: "slow",
images: [],
position: "center center"
}, settings);
addImages();
doFade();
function addImages(){
var hide = false;
jsSlider.html("");
for(i in options.images){
var div = $("<div>").attr("id", "jsSlideShow-" + i).addClass("jsSlideShow-img-block").css({
width: "100%",
height: "100%",
backgroundImage: "url('" + options.images[i] + "')",
backgroundPosition: options.position,
backgroundRepeat: "no-repeat",
position: "absolute"
});
if(hide){
div.css({display: "none"});
}
hide = true;
jsSlider.append(div);
}
}
function doFade(){
fqTimer = setTimeout(function(){
fade();
}, options.frequency);
}
function fade(){
current = jsSlider.children("div.jsSlideShow-img-block:nth-child(" + counter + ")");
current.fadeOut(options.speed);
counter++;
if(counter === options.images.length + 1){
counter = 1;
}
current = jsSlider.children("div.jsSlideShow-img-block:nth-child(" + counter + ")");
current.fadeIn(options.speed, function(){
doFade();
});
}
return this;
};
})(jQuery);
那麼,無論何時調用'.jsSlideShow',都會創建一個新的超時。所以你可能會創建多個「併發」超時,它們在相同的元素上工作,並因此以某種方式相互影響。 –
@FelixKling是啊...那麼,我怎樣才能創建每個超時? –