5

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 comes 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 commented the line where I want to add delay/wait/sleep.

Community
  • 1
  • 1
Mayank Gupta
  • 193
  • 2
  • 16
  • 1
    You should rewrite your code to make it working asynchronously. So instead of loop you can use function and `setTimeout` – Regent Mar 03 '15 at 11:31
  • 1
    use setTimeout or setInterval – Pushker Yadav Mar 03 '15 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 Mar 03 '15 at 11:37
  • @Pushkar tried both of them but as those are asynchronous so was not able to bind data synchronously..I have to bind data one by one and also in the same order it is in the object....I will also add the JS Object... – Mayank Gupta Mar 03 '15 at 11:38
  • 1
    @MayankGupta something like [this fiddle](http://jsfiddle.net/vvtu8acs/1/). – Regent Mar 03 '15 at 11:46
  • @Thanks Regent :-) I have used ur JSFiddle code..It is working fine for me..Thank YOU! – Mayank Gupta Mar 03 '15 at 12:04
  • 1
    @MayankGupta you're welcome. 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 Mar 03 '15 at 12:08
  • Yeah please.. I really accept ur answer..only problem is I do not have enough reputation currently...Please post I will accept your answer.. :-) – Mayank Gupta Mar 03 '15 at 12:10
  • @MayankGupta I have posted an answer. With slightly updated code, which works just the same way, but looks a little better. – Regent Mar 03 '15 at 12:18
  • @Regent Accepted... :-) Just need 4 more reputation Point to up-vote ur answer... :-p – Mayank Gupta Mar 03 '15 at 12:24

3 Answers3

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);
Regent
  • 5,142
  • 3
  • 21
  • 35
1

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);
bastos.sergio
  • 6,684
  • 4
  • 26
  • 36
  • 1
    `eval` is quite bad idea. What is the problem with `function() { process(i + 1); }`? – Regent Mar 03 '15 at 11:51
  • @Regent: Thank You So much for such a good answer...I am now able to achieve this...I have used ur JSFiddle link with very minor changes in code and it is now working for me...Thanks!! My reputation is less so not able to vote up ur answer... :-p Thanks to others too to help me resolve this as earlier as possible.... – Mayank Gupta Mar 03 '15 at 12:06
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();
ninhjs.dev
  • 7,203
  • 1
  • 49
  • 35