如何使用jQuery队列进行无限循环

时间:2019-09-13 11:47:22

标签: javascript jquery queue

页面加载后,我的代码翻转了6个图块。 效果很好。

var flipTiles = function() {
    $('.flip-tile').each(function( i, el ) {
        var elDelay = $(el).data('delay');
        $(el).delay(elDelay).queue(function() {
            $(this).flip(true);
            $(this).dequeue();
        });
    });
};

flipTiles();

我的问题是我该如何做才能使瓷砖不断翻转。就像那里的页面加载和瓷砖翻转有自己的延迟。在所有磁贴翻转之后,我想重新启动序列并将其翻转回原位。

感谢您的帮助! 在此先感谢:)

2 个答案:

答案 0 :(得分:1)

您需要解开循环,并使每个步骤依次触发下一个步骤,请参见注释:

var flipTiles = function() {
    // Grab the tiles
    var tiles = $('.flip-tile');
    // Start with the first tile
    var i = 0;
    // Do that tile
    next();
    function next() {
        var tile = tiles.eq(i);
        tile.delay(tile.data('delay')).queue(function() {
            tile.flip(true);
            tile.dequeue();
            // Increment `i`, wrap-around at the end
            i = (i + 1) % tiles.length;
            // Do the next tile
            next();
        });
    }
};

flipTiles();

如果您想取消它,请返回呼叫者可以用来执行的操作:

var flipTiles = function() {
    var running = true;
    // Grab the tiles
    var tiles = $('.flip-tile');
    // Start with the first tile
    var i = 0;
    // Do that tile
    next();
    // Return something the caller can use to cancel
    return function() {
        running = false;
    };
    function next() {
        if (!running) {
            return;
        }
        var tile = tiles.eq(i);
        tile.delay(tile.data('delay')).queue(function() {
            tile.flip(true);
            tile.dequeue();
            // Increment `i`, wrap-around at the end
            i = (i + 1) % tiles.length;
            // Do the next tile
            next();
        });
    }
};

var cancel = flipTiles();
// (later)
cancel();

答案 1 :(得分:0)

要“永远循环”,您可以使用setTimeout事件:

myVar = setTimeout(function() { flipTiles(); }, 3000); // 3000 is the value in milliseconds to repeat the command

停止“循环”使用

clearTimeout(myVar);