简体   繁体   English

如何在具有不同超时长度的循环中使用setTimeout?

[英]How can I use setTimeout within a loop with different lengths of timeout?

var playlist = [    
        ['Message 1','1000'],
        ['Message 2','6000'],
        ['Message 3','1000'],
        ['Message 4','8000']
    ];
    for (i = 0; i < playlist.length; i++) {
       setTimeout((function(x) { return function() { 
          $("content").empty().append("<p>" + playlist[x][0] + " timeout: " + playlist[x][1] + "</p>");
       }; })(i), playlist[i][1]*i)
    }   

I'm trying to create a timer where the length of each setTimeout interval varies depending on a variable stored in an array. 我正在尝试创建一个计时器,其中每个setTimeout间隔的长度根据存储在数组中的变量而变化。 For example I am expecting 'Message 1' to be displayed for 1 second, followed by 'Message 2' displayed for 6 seconds, and so on through the array. 例如,我期望“消息1”显示1秒,然后显示“消息2”显示6秒,依此类推。

However, the messages appear in an unexpected order, and the periods which they are on screen doesn't appear to relate to the corresponding delay I've specified in the array. 但是,消息以意外的顺序出现,并且它们在屏幕上显示的时间段似乎与我在数组中指定的相应延迟无关。

Ideally I'd also like the process to loop back to the start of the array once it gets to the end. 理想情况下,我还希望该过程在到达数组末尾时可以循环回到数组的开头。

Any help would be much appreciated! 任何帮助将非常感激!

Edit: with the looping condition: 编辑:循环条件:

var timer = null;
var index = -1;
var playlist = [
    { message: "Message 1", duration: 1000 },
    { message: "Message 2", duration: 6000 },
    { message: "Message 3", duration: 1000 },
    { message: "Message 4", duration: 8000 }
];

function displayNextMessage() {

    // If the next message exists...
    if (playlist[++index]) {

        // ...do something with the message here...
        console.log(playlist[index].message);

        // ...and queue the next message.
        timer = setTimeout(function () {
            displayNextMessage();
        }, playlist[index].duration);
    }

    // Otherwise, loop back to the beginning.
    else {
        index = -1;
        displayNextMessage();
    }
}

displayNextMessage();

Then, to stop the loop, you can call: 然后,要停止循环,可以调用:

clearTimeout(timer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM