0

I want to write a code that capture an object asynchronously, so it needs to wait for a while. When it gets the object, it stops waiting and move on. So far this what I have:

function captureObject(obj,id) {
    var i =1;
    while (obj.value === '' && i<10) {
        i++;
        (function(i,obj) {
            setTimeout(
                function() { 
                    if(obj.value === '') {
                        // do stuff here
                        return true;
                    }
                    return false;
                },
                1000 * i
            );
        })(i,obj);
    }
}

Basically I want to achieve: if obj.value is an empty string, keep waiting until it reaches 10 seconds and return true. If within 10 seconds it gets something, return false. But the code doesn't work.

Any suggestion?

Cerbrus
  • 60,471
  • 15
  • 115
  • 132
ethereal1m
  • 121
  • 2
  • 11
  • 2
    JavaScript is meant to be synchronous, so the concept of "wait until something happens, then continue" doesn't really exist. At best, you can implement "wait until something happens, then *do this specific thing*", but there's no real pause/resume in JavaScript. – Mr. Llama Jun 30 '15 at 17:56
  • 2
    once you started with asyncronous calls you cannot just return. Use callbacks or promises – smnbbrv Jun 30 '15 at 17:56
  • 1
    _"[How can I make a program wait for a variable change in javascript?](http://stackoverflow.com/questions/3635924/)"_ may be a better dupe, on second thought. – Cerbrus Jun 30 '15 at 17:58
  • OK thanks you guys, let me just close this questions. Thanks for the help – ethereal1m Jun 30 '15 at 18:01

0 Answers0