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

白昼怎懂夜的黑 提交于 2019-12-04 11:07:57

问题


I have several ASP.NET UpdatePanels, each with an AsyncPostBackTrigger tied to the same button's serverside click event. Since only one UpdatePanel can be doing its thing at a time, I use .get_isInAsyncPostBack() of the PageRequestManager to prevent a user from being able to access another part of the page until the async postback is complete.

Another part of this page needs to dynamically update multiple update panels consecutively. Since the update panels use async triggers, calling __doPostBack("<%=ButtonName.ClientID %>", 'PanelId'); fires asynchonously. Because of this, it will quickly move along to the next iteration of the loop and try to update the next panel. However, the second iteration fails because there is already another update panel doing an async postback.

Ideally, there would be a way to wait until .get_isInAsyncPostBack() returns false without blocking other client activity.

Research has lead me to a lot people with my problem, almost all of whom are advised to use setTimeOut(). I do not thing this will work for me. I don't want to wait for a specified amount of time before executing a function. I simply want my Javascript to wait while another script is running, preferably wait until a specific condition is true.

I understand that many will probably want to suggest that I rethink my model. It's actually not my model, but one that was handed to our development team that is currently a total mess under the hood. Due to time contraints, rewriting the model is not an option. The only option is to make this work. I think that if I had a way to make the client code wait without blocking, my problem would be solved.


回答1:


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
  }
}



回答2:


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
  }
}



回答3:


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...
   }
}



回答4:


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



来源:https://stackoverflow.com/questions/12841568/javascript-non-blocking-way-to-wait-until-a-condition-is-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!