Javascript:延迟遍历数组 [英] Javascript: Loop through Array with Delay

查看:125
本文介绍了Javascript:延迟遍历数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to loop through an array, but want to output each value of the array with a delay. This is what my current understanding is on how it should work:

编辑

请求的JS小提琴: 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函数内部.但是我不知道如何使它起作用.

Yet, it does not work, and I believe it might be, because the arguments in the "for" loop have to be inside the setTimeout function. Yet I don't know how to make it work.

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

All I get is every value of the array at once, but I want them appear with a delay. How do I do that?

推荐答案

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

In my example, it will show you how to loop through an array contentiously until you stop. This is to just give you an idea on how you can do the delay. Also it shows you when the value actually got displayed.

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

I would say that you could actually create a nice utility from this timer, and use it for multiple purposes and with the utility it'll stop you from repeating large chunks of code.

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:延迟遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆