2011-08-11 60 views
1

我的主頁上有一個廣告幻燈片。它由2個圖像組成。javascript幻燈片放映速度更快,爲什麼?

我預先載入了這兩張圖片,製作了new Image()並將其設置爲.src

我有一個函數giveNextName下一圖像的返回名稱(這應該是在src屬性img元素)(我這樣做,因爲很快,幻燈片將包含多於2個圖像)

所以主代碼看起來像:

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); 

所以,想法很簡單。與window.setInterval我每n秒呼叫BillBoard.change。但是,我不知道爲什麼,廣告牌變得越來越快,直到完全沒有圖片(fadeIn沒有時間執行)

我的錯誤在哪裏?

UPD。感謝Yann Ramin的鏈接。

我不應該通過window.setInterval每n秒呼叫BillBoard.change。相反,我應該在​​的回調中添加BillBoard.change的呼叫。

我的意思是這樣的代碼:

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); 
}()); 

回答