Zeeno
Zeeno

Reputation: 2721

How do I make a function execute after an asychronous function is completed?

I have a function which is processing a large amount of data, so I'm processing the data asynchronously to allow the browser update the the screen. However, I would like to call another function after that asynchronous function has completed its processing. This is what I tried to do.

function addObjects(){

object.setSrc(objFilename);
object2.setSrc(objFilname2);

} 

addObjects();

However, order doesn't matter for an asynchronous process. How do I make the second function be called after the first asynchronous function has finished processing?

Upvotes: 1

Views: 239

Answers (3)

Jiri Kriz
Jiri Kriz

Reputation: 9292

If you use e.g.

setTimeout(process1, 200);

to process asynchronously data in the function process1() you can can call the other processing function in process1():

function process1() {
    // ... process data 1 here
    // when processing data 1 finished then process data 2
    process2();   
}

You can also delay the call of process2():

function process1() {
    // ... process data 1 here
    // when processing data 1 finished then process data 2 asynchronously, but after data 1
    setTimeout(process2, 200); 
}

Upvotes: 1

flying sheep
flying sheep

Reputation: 8942

function addObjects(){
    object.setSrc(objFilename);
    object.addEventListener("onSrcSet", function() {
        object2.setSrc(objFilname2);
    }
} 

addObjects();

of course this implies that you use the right name for the event, instead of the arbitrarily chosen "onSrcSet".

and that you meant those function calls when talking about the “second” and the “first”.

Upvotes: 0

TJHeuvel
TJHeuvel

Reputation: 12608

Cant you add a callback to your function call?

As such:

function doSomethingIntensive( callback )
{
  //Do some stuff
  for(var i = 0; i < 10000; i++); //Something intensive

  //we're done, fire the callback
  if(callback)
    callback();
}

doSomethingIntensive( function()
{
 //And we're done, do some more
   doSomethingIntensive();
});

Upvotes: 1

Related Questions