如何在JS / JQUery中执行下一次循环迭代之前使代码等待x秒?

时间:2015-03-03 11:28:52

标签: javascript jquery

我已经查看了这些链接 喜欢: Javascript - Wait 5 seconds before executing next line

堆栈溢出的许多其他人。我也尝试过使用JS setTimeOut函数。

我试图模拟JS中的数据绑定,每3秒后来自Web Service。每次从WebService收到此数据后都会附加到div中。

但是为了使用JS测试和附加这些数据,我需要一些类似于Sleep()的函数。 setTimeOut以异步方式工作,因此循环的下一次迭代开始执行并且不会等待。我们如何在JS / JQuery中实现这一点。

请检查以下代码段:



linediagnosticsData = [];

linediagnosticsData.push({ Details: 'Complete - Go Live Date  Unavailable', ItemStatus: 'Tick', Title: 'Checking for Asset/Product Information' });
linediagnosticsData.push({ Details: 'Not Available', ItemStatus: 'Warning', Title: 'Line Length Summary - ' });
linediagnosticsData.push({ Details: 'Subscribers speed test results are over 31 days old', ItemStatus: 'Warning', Title: 'Line Summary' });
linediagnosticsData.push({ Details: 'Found (MPF Customer)', ItemStatus: 'Tick', Title: 'Checking for User Credentials' });
linediagnosticsData.push({ Details: 'No related incidents identified', ItemStatus: 'Tick', Title: 'Checking for Related Incidents - ' });
linediagnosticsData.push({ Details: 'The customer is subscribed for SMS updates.', ItemStatus: 'Tick', Title: 'Get Incident Subscribed' });
linediagnosticsData.push({ Details: 'Subscriber In Sync for 0 Day(s) 0 Hour(s) 0 Min(s) 0 Sec(s)', ItemStatus: 'Tick', Title: 'Checking for Sync' });
linediagnosticsData.push({ Details: 'Down(max) - 10928 kb/s Up(max) - 992 kb/s', ItemStatus: 'Warning', Title: 'Checking for Asset/Product Information' });
linediagnosticsData.push({ Details: 'Stable line', ItemStatus: 'Tick', Title: 'Checking line stability' });
linediagnosticsData.push({ Details: 'Subscriber has successfully authenticated', ItemStatus: 'Tick', Title: 'Checking for an IP Address...' });
linediagnosticsData.push({ Details: 'Subscriber has successfully connected to the network. Unable to identify any issues on this line.', ItemStatus: 'Tick', Title: 'Checking for an IP Address - Subscriber has been successfully issued an IP of 192.180.222.1' });


   for (var i = 0; i < linediagnosticsData.length; i++) {
        debugger;
        var imageURL = "/supportalcore/InternalImages/";
        switch ((linediagnosticsData[i].ItemStatus).toLowerCase()) {
            case "tick":
                imageURL = imageURL + "tick.gif";
                break;
            case "warning":
                imageURL = imageURL + "warning.gif";
                break;
            case "cross":
                imageURL = imageURL + "cross.gif";
                break;
            default:
                break;

        }
        var html =
         "<div class='nameValueImagerow'>"
        + "<div class='c1'>" + linediagnosticsData[i].Title + "</div>"
        + "<div class='c2'>" + linediagnosticsData[i].Details + "</div>"
        + "<div class='c3'>" + "<img src=" + imageURL + " alt='i'  />" + "</div>"
        + "<div class='c4'></div>"
        + "</div>";

        lineDiagnosticsBox.append(html);
        //To add wait/ Sleep so that next statement gets executed after some seconds
    }
&#13;
&#13;
&#13;

我已经评论了我想添加延迟/等待/睡眠的行。

3 个答案:

答案 0 :(得分:4)

  • 您可以使用function代替for来模仿循环。
  • setTimeout的使用允许在所需的延迟后执行下一次“迭代”。

Fiddle

var lineDiagnosticsBox = $('body');
var linediagnosticsData = [];
linediagnosticsData.push({ Details: 'Complete - Go Live Date  Unavailable', ItemStatus: 'Tick', Title: 'Checking for Asset/Product Information' });
linediagnosticsData.push({ Details: 'Not Available', ItemStatus: 'Warning', Title: 'Line Length Summary - ' });

(function loop(i) {
    var imageURL = "/supportalcore/InternalImages/";
    switch ((linediagnosticsData[i].ItemStatus).toLowerCase()) {
        case "tick":
            imageURL = imageURL + "tick.gif";
            break;
        case "warning":
            imageURL = imageURL + "warning.gif";
            break;
        case "cross":
            imageURL = imageURL + "cross.gif";
            break;
        default:
            break;            
    }
    var html = "<div class='nameValueImagerow'>"
        + "<div class='c1'>" + linediagnosticsData[i].Title + "</div>"
        + "<div class='c2'>" + linediagnosticsData[i].Details + "</div>"
        + "<div class='c3'>" + "<img src=" + imageURL + " alt='i'  />" + "</div>"
        + "<div class='c4'></div>"
        + "</div>";
    lineDiagnosticsBox.append(html);
    i++;
    if (i < linediagnosticsData.length)
    {
        setTimeout(function() { loop(i); }, 3000);
    }
})(0);

答案 1 :(得分:1)

试试这个:

function process(i) {
    if (i < linediagnosticsData.length) {
        debugger;
        var imageURL = "/supportalcore/InternalImages/";
        switch ((linediagnosticsData[i].ItemStatus).toLowerCase()) {
            case "tick":
                imageURL = imageURL + "tick.gif";
                break;
            case "warning":
                imageURL = imageURL + "warning.gif";
                break;
            case "cross":
                imageURL = imageURL + "cross.gif";
                break;
            default:
                break;

        }
        var html =
         "<div class='nameValueImagerow'>"
        + "<div class='c1'>" + linediagnosticsData[i].Title + "</div>"
        + "<div class='c2'>" + linediagnosticsData[i].Details + "</div>"
        + "<div class='c3'>" + "<img src=" + imageURL + " alt='i'  />" +     "</div>"
        + "<div class='c4'></div>"
        + "</div>";

        lineDiagnosticsBox.append(html);

        //To add wait/ Sleep so that next statement gets executed after some seconds
        var str = "process(" + (i+1) + ")";
        window.setTimeout(function(){ eval( str ) }, 1000);
    }
}

process(0);

答案 2 :(得分:0)

试试这个:

linediagnosticsData.push({ Details: 'Complete - Go Live Date  Unavailable', ItemStatus: 'Tick', Title: 'Checking for Asset/Product Information' });
linediagnosticsData.push({ Details: 'Not Available', ItemStatus: 'Warning', Title: 'Line Length Summary - ' });
linediagnosticsData.push({ Details: 'Subscribers speed test results are over 31 days old', ItemStatus: 'Warning', Title: 'Line Summary' });
linediagnosticsData.push({ Details: 'Found (MPF Customer)', ItemStatus: 'Tick', Title: 'Checking for User Credentials' });
linediagnosticsData.push({ Details: 'No related incidents identified', ItemStatus: 'Tick', Title: 'Checking for Related Incidents - ' });
linediagnosticsData.push({ Details: 'The customer is subscribed for SMS updates.', ItemStatus: 'Tick', Title: 'Get Incident Subscribed' });
linediagnosticsData.push({ Details: 'Subscriber In Sync for 0 Day(s) 0 Hour(s) 0 Min(s) 0 Sec(s)', ItemStatus: 'Tick', Title: 'Checking for Sync' });
linediagnosticsData.push({ Details: 'Down(max) - 10928 kb/s Up(max) - 992 kb/s', ItemStatus: 'Warning', Title: 'Checking for Asset/Product Information' });
linediagnosticsData.push({ Details: 'Stable line', ItemStatus: 'Tick', Title: 'Checking line stability' });
linediagnosticsData.push({ Details: 'Subscriber has successfully authenticated', ItemStatus: 'Tick', Title: 'Checking for an IP Address...' });
linediagnosticsData.push({ Details: 'Subscriber has successfully connected to the network. Unable to identify any issues on this line.', ItemStatus: 'Tick', Title: 'Checking for an IP Address - Subscriber has been successfully issued an IP of 192.180.222.1' });


var appendDiagnostic = function() {
    debugger;

    // TODO: linediagnosticsData is changed.
    var linedData = linediagnosticsData.pop();

    var imageURL = "/supportalcore/InternalImages/";
    switch ((linedData.ItemStatus).toLowerCase()) {
        case "tick":
            imageURL = imageURL + "tick.gif";
            break;
        case "warning":
            imageURL = imageURL + "warning.gif";
            break;
        case "cross":
            imageURL = imageURL + "cross.gif";
            break;
        default:
            break;

    }
    var html =
      "<div class='nameValueImagerow'>"
      + "<div class='c1'>" + linedData.Title + "</div>"
      + "<div class='c2'>" + linedData.Details + "</div>"
      + "<div class='c3'>" + "<img src=" + imageURL + " alt='i'  />" + "</div>"
      + "<div class='c4'></div>"
      + "</div>";

    lineDiagnosticsBox.append(html);
    //To add wait/ Sleep so that next statement gets executed after some seconds
    if (linediagnosticsData.length > 0) {
      setTimeout(appendDiagnostic, 3000);
    }
}

// Make the first call
appendDiagnostic();