在foreach中使用jQuery setTimeout

时间:2014-11-28 20:37:17

标签: javascript jquery json foreach settimeout

我通过'getJSON获取消息数组。 然后我想设置每条消息,等待3秒(消息在屏幕上持续3秒)并移动到下一条消息并再次等待3秒钟.. (对于每个消息我加载一个html文件并设置一个css类) 而不是那样,我的代码等待3秒,然后转到最后一条消息,没有任何超时。

$(document).ready(function(){
  $("#startAds").click(function(){
    $.getJSON("./messages.json",function(obj){
        obj.messages.forEach(function(message){
            setMessage(message);
        });})})})

var setMessage = function(message){
  setTimeout(function(){
    console.log(message.name + " Is running now");
      $("#result").load((message.template+".html"),function(responseTxt,statusTxt,xhr){
        console.log("Message "+message.name+" is on. "+"Template "+message.template+" should be up right now;");
        if(statusTxt=="success"){
            console.log(message);
            var j = 1;
            message.textLines.forEach(function(line){
                var p = "#p"+j.toString();
                $(p).text(line);
                j++;
            });
            $("#p9").text(message.textLines[0]);
            $("#p10").text(message.textLines[1]);

            $("body").addClass(message.template);
        }
        if(statusTxt=="error"){
            alert("Error: "+xhr.status+": "+xhr.statusText);
        }   
    })
},3000);}

如何通过getJSON设置我的消息并显示每条消息3秒? 感谢。

2 个答案:

答案 0 :(得分:2)

试试这个解决方案:



var messages = ['a', 'b', 'c'];

// foreach with 1 sec delay
(function showMessage(index) {
  // do smth with messages[index]
  $('<li/>').text(messages[index]).appendTo($('ul'));
  
  // do smth again with next messages[index + 1] after 1 sec
  setTimeout(function() { ++index < messages.length && showMessage(index); }, 1000);
})(0);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
&#13;
&#13;
&#13;

或使用自定义forDelayEach数组扩展方法:

&#13;
&#13;
// delayed array forEach extension method
Array.prototype.forDelayEach = function(delay, handler, thisArg) {
  var self = this;
  self.length && (function next(index) {
    handler.call(thisArg, self[index], index, self);
    setTimeout(function() { ++index < self.length && next(index); }, delay);
  })(0);
};

var messages = ['a', 'b', 'c'];

// test
messages.forDelayEach(1000, function(message) {
  $('<li/>').text(message).appendTo($('ul'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
var messages = ['msg1', 'msg2', 'msg3'], 
    logEl = document.getElementById('log');

eachDelayed(messages, log, 3000);

function eachDelayed(arr, fn, delay, index) {
  index = index || 0;
  
  if (index >= arr.length) return;
  
  fn(arr[index++]);
  
  setTimeout(eachDelayed.bind(this, arr, fn, delay, index), delay);
}

function log(msg) {
    logEl.innerHTML += msg + '<br>';
}
&#13;
<div id="log"></div>
&#13;
&#13;
&#13;