【问题标题】:jQuery setTimeout in foreachforeach中的jQuery setTimeout
【发布时间】:2015-01-27 12:31:57
【问题描述】:

我通过 '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 秒? 谢谢。

【问题讨论】:

  • 你会立即开始很多超时,因为循环不会等待任何东西,并且所有超时都会在 3 秒内触发,或者至少非常接近它,所以只有最后一个将可见。

标签: javascript jquery json foreach settimeout


【解决方案1】:

试试这个解决方案:

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>

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

// 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'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>

【讨论】:

  • 效果很好!只需要明确一个问题:这一行是否:{ ++index
  • 是的,这一行等于if (...) { ... }
【解决方案2】:

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>';
}
&lt;div id="log"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 2012-02-06
    • 1970-01-01
    • 2020-08-10
    相关资源
    最近更新 更多