1

How can I stop executing function till another function is done?

$('#div').load( 'sub.html', function() {

    //Do this once done loading the sub.html file
    setTimeout(function() { 

        //Run SomeFunction(); before doing anyhing else
        $('#tabsWrapper').removeClass('ajaxLoading');
        $('#tabsWrapper #loaderDiv').fadeIn(500);

    } , 1000);

});

I want to make sure SomeFunction() is done before doing $('#tabsWrapper').removeClass('ajaxLoading'); etc..

Any suggestion how can I achieve that? Any help much appreciated.

G_H
  • 11,739
  • 3
  • 38
  • 82
Iladarsda
  • 10,640
  • 39
  • 106
  • 170
  • return value from SomeFunction and see if it's done, could you a loop until value is returned. – Riz Oct 24 '11 at 09:17
  • use a callback on .load. http://stackoverflow.com/questions/6688958/jquery-load-callback-scrolling-css-overflow, i believe that will work. – Matt Oct 24 '11 at 09:19
  • 1
    seems to be quite normal flow of the script. is simeFunction doesnt have anything like `ajax` it will run the way you require it – Varun Oct 24 '11 at 09:19

3 Answers3

2
$('#div').load( 'sub.html', function(response, status) {

     if(status=="success"){
          //do your stuff here ..its loaded
  }

});
coolguy
  • 7,866
  • 9
  • 45
  • 71
2

Use the callback method.

Please refer to the JQuery API

Soony
  • 903
  • 9
  • 18
1

Return some value from your SomeFunction() and put in condition like this:

var result = null; // important to put it here eg before setTimeout

//Do this once done loading the sub.html file
setTimeout(function() { 

    result = SomeFunction();

    if (result === 'whatever that function returns') {
      $('#tabsWrapper').removeClass('ajaxLoading');
      $('#tabsWrapper #loaderDiv').fadeIn(500);
    }

} , 1000);

A better approach would be using self-invoking anonymous function something like this:

(function foo(){
   doStuff;

   setTimeout(foo, 500);

})()

Here setTimeout will only trigger when doStuff is finished.

Community
  • 1
  • 1
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • The quastion is - if the `SomeFunction()` is not done before `if statement` will it be skipped than? I want to make sure the order of executing is maintained. – Iladarsda Oct 24 '11 at 09:22
  • @NewUser: See the later approach :) – Sarfraz Oct 24 '11 at 09:24
  • Nearly there. Where do I put the code to be exectuted once `doStuff();` is done? Before or after `setTimeout`, or maybe inside? but how?:) – Iladarsda Oct 24 '11 at 09:33