简体   繁体   English

JavaScript:在循环之前等待n秒

[英]JavaScript: Wait n seconds before continue while loop

I have this while loop in JS. 我在JS中有这个while循环。 It tries to do something and if it doesn't work, I want it to calculate the time it will need to wait and then reloop. 它尝试做某事,如果它不起作用,我希望它计算等待然后重新循环所需的时间。

while (makeSomething() == false) {
    var wait = a + b + c;
    sleep(wait);
}

I only know setTimeout(), but as you might know it does not behave like I want it to do. 我只知道setTimeout(),但你可能知道它的行为并不像我想要的那样。

If jQuery offers a solution for it, that would be okay too. 如果jQuery为它提供了解决方案,那也没关系。

You are going to have to change how your logic works. 您将不得不改变逻辑的工作方式。 Probably means you need to break up your code. 可能意味着您需要分解代码。 Basic idea of what you want to do it: 你想做什么的基本想法:

function waitForIt(){
   if(makeSomething() == false) {
        var wait = a + b + c;
        window.setTimeout(waitForIt, wait);
   } else {
       console.log("do next step");
   }
}
waitForIt();

It depends on your intention here. 这取决于你的意图。 From your question, it seems you want to stay in the while loop until makeSomething() is true. 从您的问题来看,似乎您希望保持while循环直到makeSomething()为真。 epascarello's answer will continue thread execution because it uses setTimeout(). epascarello的答案将继续执行线程,因为它使用setTimeout()。

Technically his answer is significantly better because it does not hang the application. 从技术上讲,他的答案明显更好,因为它不会挂起应用程序。 But if you really wanted a sleep function that will stop all application processing you can use this function: 但如果你真的想要一个停止所有应用程序处理的睡眠功能,你可以使用这个功能:

    function sleepFor( sleepDuration ) {
        var now = new Date().getTime();
        while(new Date().getTime() < now + sleepDuration){ /* do nothing */ } 
    }

Note that this is generally bad practice, a user will not be able to interact with your application while the thread is asleep. 请注意,这通常是不好的做法,当线程处于睡眠状态时,用户将无法与您的应用程序进行交互。

Gathered from: What is the JavaScript version of sleep()? 聚集于: sleep()的JavaScript版本是什么?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM