我正在尝试遍历一个数组,但是想要延迟输出数组的每个值。这是我目前对它应该如何工作的理解:

编辑

要求的JS fiddle :http://jsfiddle.net/d3whkjww/

    loopThroughSplittedText: function(splittedText) {

        for (var i = 0; i < splittedText.length; i++) {
            // for each iteration console.log a word
            // and make a pause after it
            setTimeout(
                console.log(splittedText[i]),
                1000
            );
        };

    },

但是,它不起作用,我相信可能是这样,因为“for”循环中的参数必须在setTimeout函数内部。但是我不知道如何使它起作用。

我得到的只是一次数组的每个值,但我希望它们延迟出现。我怎么做?

最佳答案

在我的示例中,它将向您展示如何有争议地遍历数组直到停止。这只是给您一个有关如何执行延迟的想法。它还会在实际显示该值时向您显示。

我要说的是,您实际上可以从此计时器创建一个不错的实用程序,并将其用于多种用途,并且借助该实用程序,它将使您不再重复大量代码。

JavaScript循环示例:

var body = document.body;
var splittedText = ["Hello", "World", "How", "Are", "You", "Today"];

loopThroughArray(splittedText, function (arrayElement, loopTime) {
    body.innerHTML += arrayElement+ ": " + loopTime+ "<br/>";
}, 1000);

function loopThroughArray(array, callback, interval) {
    var newLoopTimer = new LoopTimer(function (time) {
        var element = array.shift();
        callback(element, time - start);
        array.push(element);
    }, interval);

    var start = newLoopTimer.start();
};

// Timer
function LoopTimer(render, interval) {
    var timeout;
    var lastTime;

    this.start = startLoop;
    this.stop = stopLoop;

    // Start Loop
    function startLoop() {
        timeout = setTimeout(createLoop, 0);
        lastTime = Date.now();
        return lastTime;
    }

    // Stop Loop
    function stopLoop() {
        clearTimeout(timeout);
        return lastTime;
    }

    // The actual loop
    function createLoop() {
        var thisTime = Date.now();
        var loopTime = thisTime - lastTime;
        var delay = Math.max(interval - loopTime, 0);
        timeout = setTimeout(createLoop, delay);
        lastTime = thisTime + delay;
        render(thisTime);
    }
}

关于Javascript:延迟遍历数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30865456/

10-14 15:06
查看更多