0

I really searched long on the internet for this issue. I just want to run code when a function which is called before is over. Let me explain on this example:

var id=0;

function refreshID(){
    //refresh the div
}

function postID(){
    //some code
    refreshID();
    id=1;    
}

By calling the function postID, the function refreshID will executed, then the variable id is set to 1. But I think the variable is set to 1 before the function refreshID() is fully executed. So my question is: How to run code (In this case change the value of the variable), when another function is over, when its completely executed.

regards

emerson.marini
  • 9,331
  • 2
  • 29
  • 46
hookieV2
  • 15
  • 4

4 Answers4

0

JavaScript does not offer concurrent access to variables to refreshID will be fully executed before you set id to 1.

Florian Salihovic
  • 3,921
  • 2
  • 19
  • 26
0

You could use a callback:

function refreshID(doWhateverElse){
    //refresh the div
    doWhateverElse();
}

function postID(){
    //some code
    refreshID(function() { 
        id=1;
    } );
}

The function passed in as a parameter to refreshID will only be run once the div has been refreshed.

Jonathan Sayce
  • 9,359
  • 5
  • 37
  • 51
0

JavaScript is single-threaded, so code is guaranteed to be run linearly -- it'll never skip lines of code.

In your example, id = 1 is always executed after refreshID has returned. What makes things trickier is that refreshID may set things to be done asynchronously, e.g. using setTimeout, in which case refreshID will return before the callback is run. In that case, it might be useful to pass a callback to the function or use promises.

For example:

var id = 0;

function refreshID(cb) {
    setTimeout(function () {
        // your work
        // ...

        cb();
    });
}

function postID(){
    // some code
    refreshID(function () { id = 1; });
}
Casey Chu
  • 25,069
  • 10
  • 40
  • 59
0

No, id will not get assigned 1 before the call to refreshID has finished. It is ensured by the javascript engine itself. As said in other answers it is single threaded and there is only one line of execution. BUT there is no need for ajax of any other network/timeout/interval/... to explain why you can think you have problems in your code execution. If function refreshID is making any kind of change to the html, remember that these changes will be not visible until the execution of the script ends.

MC ND
  • 69,615
  • 8
  • 84
  • 126