Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make code wait x seconds before executing next iteration of loop in JS/ JQUery?

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.

like image 215
Mayank Gupta Avatar asked Mar 03 '15 11:03

Mayank Gupta


People also ask

How do you sleep 5 seconds in JavaScript?

import { setTimeout } from "timers/promises"; const yourFunction = async () => { await setTimeout(5000); console. log("Waited 5s"); await setTimeout(5000); console.

How do you make a loop wait?

Your loop needs to wait for the asynchronous task to complete on each round of the for loop. To make this happen, mark your function asynchronous using the async keyword, and place an await keyword in front of the action you want to wait for.


1 Answers

  • 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);
like image 137
Regent Avatar answered Sep 30 '22 05:09

Regent