0

I have wrote following code;

var isValid = undefined;

alert(codeEditAddress());

function codeEditAddress() {
      test();
      return waitFor(function() { return isValid != undefined }, function(){return isValid});
}

function test(){
       setTimeout(function(){isValid = true;}, 1000);

}
function waitFor(fnReady, fnCallback) {
            var check = function () {
                if (fnReady()) {
                    fnCallback();
                }
                else {
                    setTimeout(check, 100);  // wait another 100ms, and try again
                }
            };
            check();
}

I see "undefined" in alert.

Expected result - to see "true" with delay 1 sec.

What do I wrong?

P.S. demo

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • The calls to `setTimeout()` return immediately. After the 100 milliseconds have elapsed, the system will call the "check" function. – Pointy Mar 01 '15 at 16:45
  • Is it possible to refactor this code to achieve desired result? – gstackoverflow Mar 01 '15 at 16:48
  • 1
    You have to embrace the asynchronous nature of browser-based JavaScript architecture. You cannot make the thread of execution "wait" like you can in (for example) Java with `Thread.sleep()`. – Pointy Mar 01 '15 at 16:51
  • Can you show conrete code? your explanation is enough abstract – gstackoverflow Mar 01 '15 at 16:52
  • 1
    You have to perform the delayed actions *inside the callback function*. It doesn't make sense to expect a return value (note that your "waitFor" function doesn't even include a `return` statement). [Here is a modified version of your jsfiddle.](http://jsfiddle.net/214190tj/) – Pointy Mar 01 '15 at 17:15
  • It is wrong example. http://jsfiddle.net/214190tj/1/ **777** alert executes before **Finished!** – gstackoverflow Mar 01 '15 at 17:19
  • Right, because **calls to `setTimeout()` return immediately.** – Pointy Mar 01 '15 at 17:23
  • But I need await)) like in java – gstackoverflow Mar 01 '15 at 17:24
  • 1
    You cannot have that in JavaScript. The only solution is to put the code in the callback function(s). There is no equivalent of `Thread.sleep()`. – Pointy Mar 01 '15 at 17:25
  • not friendly language( – gstackoverflow Mar 01 '15 at 17:30
  • @Pointy please read http://stackoverflow.com/questions/28796705/how-to-check-adress-validity it is a reason of this question – gstackoverflow Mar 01 '15 at 17:33

0 Answers0