jQuery setInterval滞后

时间:2013-11-21 15:16:13

标签: javascript jquery

我在项目 http://jsbin.com/uceqi/357

中使用此jQuery代码
$(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秒就有这么多元素我会得到那个令人烦恼的迟滞。

我想我可以切割每个元素,除了前几个元素并将它们存储在某个地方一段时间。但我真的不知道该怎么做。

当然,我可以将它们附加到一个看不见的div上,然后从中取出它们,但我觉得这很糟糕。那么我应该在哪里存储这么多物品?

缓存?

1 个答案:

答案 0 :(得分:1)

您无法从JavaScript(浏览器)计时器获得任何保证精度,但您可以使用setTimeout()而不是setInterval()来适应条件,并自适应地计算每个超时。< / p>

基本机制如下:

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

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

“adaptiveTimer”函数需要一个间隔(这里以毫秒为单位)和一个工作函数,它将执行您希望在每个间隔上完成的任何工作。功能(外部)记录当前挂钟时间并在第一个周期运行内部“滴答”功能。

“tick”函数运行worker。然后再次检查挂钟时间,并计算当前时间与下一个周期应运行的标称时间之间的毫秒数。该差异用作下一次迭代的超时值。

如果工作人员花费更多或更少的时间来运行,那么该计算将调整超时间隔以(稍微)弥补更改。