How to execute a javascript/jquery function only after the completion of another function?

好久不见. 提交于 2020-01-06 07:02:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!