简体   繁体   中英

Javascript wait for variable

I have a service variable that is initialized :

service = new google.gdata.calendar.CalendarService('timeless');

This happens in a callback function. My problem is that I have other functions that rely on the service variable. If I call them too soon the variable is undefined and the script does nothing.

The main problem would be if the user would try to click on a button that calls one of these functions. How can I make the function wait? If I use a cutsom spinlock it would kill the browser.

I need some kind of pseudo-mutex or wait/sleep function. I don't think that setTimeout would help.

Thanks.

how about something like this?

$(initservice);

function initOtherSTuff(){
//init other stuff
}

function initService(initCalled){
    if(!initCalled){
        service = new google.gdata.calendar.CalendarService('timeless');
    }
    else if(!service){
        window.setTimeout(function(){initService(true);},500);
    }
    else{
        initOtherStuff();
    }

Introduce a level of indirection: rather than having the onclick() code call such functions directly, have it place the call on a variable that initially contains a function that does nothing (or perhaps displays an error message, or otherwise handles the condition), then once service is initialised gets the real function assigned to it:

.
.
var indirection = { func1: function(){}, func2: function(){} }
.
.
<element onClick = "indirection.func1()"></element>
.
.
service = new google.gdata.calendar.CalendarService('timeless');
indirection.func1 = functionThatUsesService
.
.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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