javascript - How to make code wait x seconds before executing next iteration of loop in JS JQUery? - Stack Overflow

I have already looked at the links like:Javascript - Wait 5 seconds before executing next lineand man

I have already looked at the links like: Javascript - Wait 5 seconds before executing next line

and many others on stack overflow. Also I have tried using JS setTimeOut function for this.

I am trying to simulate a data bind in JS which es from Web Service after every 3 seconds. This data is appended in a div after every time received from WebService.

But for testing and appending this data using JS, I need some function similar to Sleep(). setTimeOut works asynchronously so next iteration of loop start executing and doesn't wait. How can we achieve this in JS/JQuery.

Please check code snippet below:

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
    }

I have already looked at the links like: Javascript - Wait 5 seconds before executing next line

and many others on stack overflow. Also I have tried using JS setTimeOut function for this.

I am trying to simulate a data bind in JS which es from Web Service after every 3 seconds. This data is appended in a div after every time received from WebService.

But for testing and appending this data using JS, I need some function similar to Sleep(). setTimeOut works asynchronously so next iteration of loop start executing and doesn't wait. How can we achieve this in JS/JQuery.

Please check code snippet below:

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
    }

I have mented the line where I want to add delay/wait/sleep.

Share Improve this question edited May 23, 2017 at 12:28 CommunityBot 11 silver badge asked Mar 3, 2015 at 11:28 Mayank GuptaMayank Gupta 1932 silver badges16 bronze badges 10
  • 1 You should rewrite your code to make it working asynchronously. So instead of loop you can use function and setTimeout – Regent Commented Mar 3, 2015 at 11:31
  • 1 use setTimeout or setInterval – Pushker Yadav Commented Mar 3, 2015 at 11:36
  • I have tried doing that too...But how can you achieve to bind data from nameValuePair.. only way I find is to bind data using "for loop"...please suggest if you have another? – Mayank Gupta Commented Mar 3, 2015 at 11:37
  • 1 @MayankGupta something like this fiddle. – Regent Commented Mar 3, 2015 at 11:46
  • 1 @MayankGupta you're wele. Every solved question in SO should have accepted answer, so either you can delete your question or accept someone's answer or I can post my code as an answer if you are ready to accept it. – Regent Commented Mar 3, 2015 at 12:08
 |  Show 5 more ments

3 Answers 3

Reset to default 5
  • You can use function instead of for to imitate loop.
  • Usage of setTimeout allows to execute next "iteration" after required delay.

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);

Try this:

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);

Try this:

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();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745273611a4619901.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信