javascript - waiting a function to complete - Stack Overflow

I have 2 functions. The second one is faster than the first one,how could the function wait toplete f

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
Add a ment  | 

4 Answers 4

Reset to default 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);
}

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

相关推荐

  • javascript - waiting a function to complete - Stack Overflow

    I have 2 functions. The second one is faster than the first one,how could the function wait toplete f

    2天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信