Javascript: Non-blocking way to wait until a condition is true

耗尽温柔 提交于 2019-12-03 06:46:32
Marian Bazalik

There is no such functionality such as wait or sleep in javascript, since it would stop browser from responding.

In your case I would go with something similar to following:

function wait(){
  if (!condition){
    setTimeout(wait,100);
  } else {
    // CODE GOES IN HERE
  }
}
CoderDennis

It's easy to make a mistake when calling setTimeout that will cause the JavaScript call stack to fill up. If your function has parameters, you need to pass those in at the end of the setTimeout parameter list like this:

function wait(param1, param2){
  if (!condition){
    setTimeout(wait, 100, param1, param2);
  } else {
    // CODE GOES IN HERE
  }
}

If you pass parameters or even include empty () after the name of the function, it will be executed immediately and fill up the stack.

// This is the wrong way to do it!    
function wait(param1, param2){
  if (!condition){
    setTimeout(wait(param1, param2), 100); // you'll get max call stack error if you do this!
  } else {
    // CODE GOES IN HERE
  }
}

This function calls condFunc which should return true when condition is met. When that happens readyFunc is called. checkInterval sets checking rate in milliseconds

       var wait = function(condFunc, readyFunc, checkInterval) {
            var checkFunc = function() {
                if(condFunc()) {
                    readyFunc(); 
                }
                else
                {
                    setTimeout(checkFunc, checkInterval);
                }
            };
            checkFunc();
        };

Usage:

       wait(
            function() { return new Date().getSeconds() == 10; }, 
            function() { console.log("Done"); },
            100
        );

prints "Done" when current time is 10 seconds after minute

I needed to slow down a process and came up with a helpful little method.

wait = (seconds) => 
   new Promise(resolve => 
      setTimeout(() => resolve(true), seconds * 1000)
   );

And you can use it like this.

doWork = async() => {
   if(await this.wait(3)) {
       // After 3 seconds do something...
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!