I have 2 functions. The second one is faster than the first one,how could the function wait to plete first one's work?
function1(); // slow
function2(); // fast
I have 2 functions. The second one is faster than the first one,how could the function wait to plete first one's work?
function1(); // slow
function2(); // fast
Share
Improve this question
edited Oct 27, 2012 at 12:15
Sibu
4,6172 gold badges29 silver badges38 bronze badges
asked Oct 27, 2012 at 12:09
Dorukcan KişinDorukcan Kişin
1,1312 gold badges14 silver badges29 bronze badges
4 Answers
Reset to default 4JavaScript is imperative and single-threaded, it just works like this. function2()
won't start until function1()
finishes.
If by slow you mean calling asynchronously some external service via AJAX, then we're talking. function1()
must provide some sort of callback so that when asynchronous request finishes, function2()
is called:
function1(function2);
The implementation is trivial, e.g. using jQuery:
function function1(callback) {
$.ajax({url: 'some-url'}).done(callback);
}
If functions are to be called asynchronously, aside from the obvious callback approach, their sequencing could be based on the events framework. You could add an event listener with function1 as a handler, and trigger that event within function2.
You must be using some AJAX request. So, after ajax plete call callback function like:
function1 = new function(callback) {
$.ajax({...}).done(callback());
}
function1(function2);
If your calling one function after the other then it will finish the first either it may be slow or fast.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744846689a4596881.html
评论列表(0条)