开发者

Javascript wait for variable

开发者 https://www.devze.com 2023-02-03 01:47 出处:网络
I have a servi开发者_如何学Cce variable that is initialized : service = new google.gdata.calendar.CalendarService(\'timeless\');

I have a servi开发者_如何学Cce 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.


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


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();
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号