简体   繁体   English

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

[英]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 我已经看过像这样的链接: Javascript - 在执行下一行之前等待5秒

and many others on stack overflow. 和许多其他堆栈溢出。 Also I have tried using JS setTimeOut function for this. 我也尝试过使用JS setTimeOut函数。

I am trying to simulate a data bind in JS which comes from Web Service after every 3 seconds. 我试图模拟JS中的数据绑定,每3秒后来自Web服务。 This data is appended in a div after every time received from WebService. 每次从WebService收到后,此数据都会附加在div中。

But for testing and appending this data using JS, I need some function similar to Sleep(). 但是为了使用JS测试和附加这些数据,我需要一些类似于Sleep()的函数。 setTimeOut works asynchronously so next iteration of loop start executing and doesn't wait. setTimeOut异步工作,因此循环的下一次迭代开始执行并且不等待。 How can we achieve this in JS/JQuery. 我们如何在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. 我已经评论了我想添加延迟/等待/睡眠的行。

  • You can use function instead of for to imitate loop. 您可以使用function ,而不是for模仿循环。
  • Usage of setTimeout allows to execute next "iteration" after required delay. 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);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何进行循环以等待元素,然后再进行下一次迭代 - How to make for loop wait for an element before moving to next iteration Javascript:等待循环中的函数在下一次迭代之前完成执行 - Javascript: wait for function in loop to finish executing before next iteration 在执行下一行代码之前等待几秒钟? - Wait for a few seconds before executing next line of code? 我如何让 javascript 循环在开始下一次循环之前等待循环的每次迭代完成? - How do i make javascript loop wait for each iteration of loop to finish before starting the next? 节点js for-loop在下一次迭代之前等待异步函数? - Node js for-loop wait for asynchronous function before next iteration? 在执行下一行之前等待 5 秒 - Wait 5 seconds before executing next line 如何让 Javascript 循环等待现有迭代完成,然后再开始下一个? - How do I make a Javascript loop wait for existing iteration to finsih before starting the next? 如何使循环等待db promise完成,然后再继续下一次迭代? - How do I make for loop wait for db promise to finish before it continues to next iteration? 在执行下一行代码之前,JQuery会等待几秒钟 - JQuery wait a number of seconds before the next line of code is executed 在执行下一个代码之前打字稿会等待循环完成吗? - Will typescript wait for a loop to complete before executing the next code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM