I have 2 functions. The second one is faster than the first one,how could the function wait to complete 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 complete first one's work?
function1(); // slow
function2(); // fast
JavaScript 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);
}
You must be using some AJAX request. So, after ajax complete call callback function like:
function1 = new function(callback) {
$.ajax({...}).done(callback());
}
function1(function2);
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.
If your calling one function after the other then it will finish the first either it may be slow or fast.