2013-11-21 34 views
1

我使用這個jQuery代碼在我的項目http://jsbin.com/uceqi/357jQuery的setInterval的滯後

$(window).load(function() { 
    arrangeBoxes(); 
    setInterval('shiftLeft()', 3000); 
}); 

// arrange the boxes to be aligned in a row 
function arrangeBoxes() { 
    $('.box').each(function(i, item) { 
     var position = $('#window').position().left + 3 + i * ($(item).width() + 10); 
     $(item).css('left', position+'px') 
    }); 
} 

// shifts all the boxes to the left, then checks if any left the window 
function shiftLeft() { 
    $('.box').animate({'left' : "-=100px"}, 3000, 'linear', checkEdge()); 
} 

// returns the new location for the box that exited the window 
function getNewPosition() { 
    return $('.box:last').position().left + $('.box:last').outerWidth() + 10; 
} 

// if the box is outside the window, move it to the end 
function checkEdge() { 
    var windowsLeftEdge = $('#window').position().left; 

    $('.box').each(function(i, box) { 
     // right edge of the sliding box 
     var boxRightEdge = $(box).position().left + $(box).width(); 

     // position of last box + width + 10px 
     var newPosition = getNewPosition(); 

     if (parseFloat(boxRightEdge) < parseFloat(windowsLeftEdge)) { 
      $(box).css('left', newPosition); 
      $(box).remove().appendTo('#window'); 
      first = $('.box:first').attr('class'); 
     } 
    }); 
} 

有了這麼多的元素每隔3秒,我得到那個有點惱人滯後。

我想我可以切片的每一個元素,除了前幾個,並將它們存儲在某個地方一段時間。但我真的不知道該怎麼做。

我當然可以追加他們的無形的股利和他們走他們,但我認爲這是很討厭。那麼我應該在哪裏存儲這麼多的對象呢?

Cookie?

+3

我會通過不使用setInterval的開始,我莫名其妙地懷疑動畫是精確到足以完成恰好3秒,這可能導致在隊列中建立隨着時間的推移。此外,您正在執行'checkEdge',而不是在動畫完成時執行。 –

+0

請注意,JS間隔會受到處理器負載的影響 - 因此很可能是您的滯後原因。 – eithed

回答

1

JavaScript(瀏覽器)定時器無法保證任何精度,但是您可以適應條件,因爲它們使用setTimeout()而不是setInterval()進行更改,並自適應地計算每個超時。

的基本機制是這樣的:

function adaptiveTimer(interval, worker) { 
    function tick() { 
    worker(); 
    setTimeout(tick, (previous += interval) - Date.now()); 
    } 

    var previous = Date.now(); 
    tick(); 
} 

的「adaptiveTimer」功能需要一個時間間隔(這裏毫秒)和工人功能力所能及的工作,你想在每個區間做到這一點會做。該功能(外部功能)記錄了當前的掛鐘時間並運行第一個週期的內部「滴答」功能。

「打勾」功能運行工作人員。然後它再次檢查掛鐘時間,並計算當前時間與下一個週期應運行的標稱時間之間的毫秒數。該差異被用作下一次迭代的超時值。

如果工人需要更多或更少的時間來運行,該計算將適應超時間隔(有點)彌補變化。