Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

jquery - How to add a callback to a function in javascript

I have two javascript functions

function one () {
   do something long... like writing jpgfile on disk
}

function two () {
   do something fast... like show the file
}

I call it (in jQuery) like this

 one ();
 two ();

Because function two needs the link file from function one, i need to be sure the execution is completed... so getting the function two in the callback of function one should be the trick.. but how to do that ?

note : I did put an alert ('aaa') between those two functions to let function one complete, and it worked fine... when the alert is commented (removed) nothing works anymore !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You only need to use a callback if you are doing something asynchronous, otherwise it doesn't matter how long something takes, the next function won't run until the first has finished.

A callback is just passing a function as an argument, and then calling it when done.

function one (callback) {
   do something long... like writing jpgfile on disk
   callback();
}

function two () {
   do something fast... like show the file
}

one(two);

Obviously, if you are doing something asynchronous, then you need something that will tell you when it is finished (such as an event firing).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...