问题
I know this is a simple question, but I don't really know how to do it. I'm executing two functions in my code, 'luxboxEngine' and 'fitToScreen', the latter of which requires the completion of the former. How do I tell 'fitToScreen' to only execute after 'luxboxEngine' has completed? Right now I have this, which gets the desired results:
luxboxEngine(self);
setTimeout(fitToScreen, 1000);
...But I know that's not a good solution. I've read about callback functions, but I'm afraid I don't really get what they are / how to incorporate them. Thanks for reading.
EDIT: So as Sudharsan Sri and Brian McGinity answered below, a callback is the solution. Here's the code I used to get what I need in my program:
luxboxEngine(self, function () {
fitToScreen();
});
That fires the fitToScreen function after the completion of luxboxEngine.
回答1:
Use a callback:
luxboxEngine(self , function() { fitToScreen(); });
回答2:
like a callback? Pass the function as a argument then call it:
fitToScreen( function(){luxBoxEginie();} );
function fitToScreen( cb ) {
//// do somethings
cb()
}
or
luxboxEngine(self, function (){ fitToScreen(); });
function luxboxEngine( s, cb)} {
// do somethings
cb(); //execute the callback function
}
fitToScreen() is passed as an argument into luxboxEngine(). fitToScreen() waits to to be executed, and runs only when you do: cb()
回答3:
luxboxEngine(self); //Executes, returns undefined, nothing happens with return value
fitToScreen(); //The first one is done by the time we get here
来源:https://stackoverflow.com/questions/21692705/how-to-execute-a-javascript-jquery-function-only-after-the-completion-of-another