3

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
Sibu
  • 4,609
  • 2
  • 26
  • 38
Dorukcan Kişin
  • 1,121
  • 2
  • 14
  • 29

4 Answers4

4

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);
}
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
1

You must be using some AJAX request. So, after ajax complete call callback function like:

function1 = new function(callback) {
    $.ajax({...}).done(callback());
}

function1(function2);
Mustafa Genç
  • 2,569
  • 19
  • 34
1

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.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
-1

If your calling one function after the other then it will finish the first either it may be slow or fast.

andy
  • 5,979
  • 2
  • 27
  • 49