开发者

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

开发者 https://www.devze.com 2023-04-03 06:37 出处:网络
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 afte

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(objFilname开发者_JAVA百科2);

} 

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?


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


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


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

0

精彩评论

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