在loopin javascript中添加setInterval函数

时间:2015-12-10 02:45:03

标签: javascript jquery

我写了一个for循环来抓取我的变量对象中的信息,现在我试图在我的循环中使用setInterval函数,它将遍历显示1个数据的数据,同时循环执行命令:

var i = 0;
var twitterData = {
    tweet1 : [{
        user: {
            profile_image_url : "assets/avatar.png",
            name : "@Hodor"
        },
        text : "Hodor Hodor Hodor Hodor Hodor Hodor Hodor..... Hodor"
    }],
    tweet2 : [{
        user: {
            profile_image_url : "assets/avatar.png",
            name : "@johnsnow"
        },
        text : "Someone once said that I know nothing..."
    }],
    tweet3 : [{
        user: {
            profile_image_url : "assets/avatar.png",
            name : "@drwho"
        },
        text : "Fantastic!"
    }]
};

sqTweetData = getTweetData();

function getTweetData() {
    return twitterData;
}

for (var k in sqTweetData) {

    // Gives me object {tweet1: Array[1], tweet2: Array[1]. tweet3: Array[1]}
    console.log("sqTweetData = ",sqTweetData);

    for (var l = 0; l < sqTweetData[k].length; l++) {
        var foo = sqTweetData[k][l]
        // Loops sqTweetData and returns object {user: object, text: "hodor hodor hodor etc"}
        console.log("foo = ", foo);

        setInterval(function() {
            // returns the last object for tweet3 and does NOT display tweet1, tweet2, tweet3 in that order over 3000ms
            console.log(foo);
            i++;
        }, 3000);
    }

}

我遇到的问题是,一旦进入setInterval函数,它只会显示最后一个数据(即tweet3)并反复循环。它不是循环遍历数据并按顺序显示它。想法?

1 个答案:

答案 0 :(得分:0)

var i = 0;
var twitterData = {
  tweet1: [{
    user: {
      profile_image_url: "assets/avatar.png",
      name: "@Hodor"
    },
    text: "Hodor Hodor Hodor Hodor Hodor Hodor Hodor..... Hodor"
  }],
  tweet2: [{
    user: {
      profile_image_url: "assets/avatar.png",
      name: "@johnsnow"
    },
    text: "Someone once said that I know nothing..."
  }],
  tweet3: [{
    user: {
      profile_image_url: "assets/avatar.png",
      name: "@drwho"
    },
    text: "Fantastic!"
  }]
};

sqTweetData = getTweetData();

function getTweetData() {
  return twitterData;
}

// count variable to increment timeout 
count = 1;
for (var k in sqTweetData) {

  // use self executing anonymous function to create a new scope
  (function(k) {
    for (var l = 0; l < sqTweetData[k].length; l++) {
      var foo = sqTweetData[k][l]

      // using setTimeout and incrementing the delay by count
      setTimeout(function() {
        console.log(foo);
        i++;
      }, 3000 * count);
    }
    count++;
  })(k)
}

编辑:首先设置了setInterval而不是超时。也是封闭问题。使用自我实例化的函数可以解决此问题。最后一件事是需要增加setTimeout。我添加了一个计数变量,它增加了延迟,以便每个日志记录3000毫秒