简体   繁体   中英

Excecute script after defined value in variable without setTimeout in javascript

I wanted to execute a script after define value in variable without setTimeout.

This is I am trying to do:

var sessionId;
function AddSessionID(e) {
    sessionId = e;
}

$(function(){
    alert(sessionId);
});

But I am getting value is undefined.

If I set a delay for this like:

$(function(){
    setTimeout(function(){
        alert(sessionId);
    }, 2000);
});

then I am getting proper value.

But I don't want to set delay for that. because session id is dynamic. it is depended to the server.

I need a call back.

This is really I wanted:

var sessionId;
    function AddSessionID(e) {
        sessionId = e;
    }

    $(function(){
        if (sessionId != undefined) {
            alert(sessionId);
    }
});

write a callback like this -

function AddSessionID(e) {
    sessionId = e;
    sessionIdReadyCallback();
}

function sessionIdReadyCallback(){
 alert(sessionId);
}

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