-1

I need to perform this step:-

  1. When document is ready,
  2. do function A,
  3. After function A is completed,
  4. perform function B, C, D

Though not exactly the answer, the following way works:-

<script>
$(document).ready(function(){
    function_a();
    setTimeout(function(){
        function_b(); 
        function_c();
        function_d();
    }, 100);
});
</script>

Surely, I cannot always depend on time delay! However, the following way is not working:-

<script>
$(document).ready(function(){
    function_a();
}).complete(function(){
    function_b(); 
    function_c();
    function_d();
});
</script>

How can the second way be improved?

user2122657
  • 155
  • 2
  • 10

4 Answers4

1
function_a();

function function_a()
{
 ........
 function_b();
}

function function_b()
{
 ........
 function_c();
}

function function_c()
{
  ........
 function_d();
}
PSR
  • 39,804
  • 41
  • 111
  • 151
1
$(document).ready(function(){
    function_a();
    function_b(); 
    function_c();
    function_d();

});

Will do the same if functions are synchronous.
For Asynchronus functions use callbacks.
This might help : How should I call 3 functions in order to execute them one after the other?

Community
  • 1
  • 1
Ajinkya
  • 22,324
  • 33
  • 110
  • 161
1

You could just do with below if function_a works synchronous.

$(document).ready(function(){
    function_a();
    function_b(); 
    function_c();
    function_d();
});

But if it works asynchronous, then function_a should provide a parameter for complete callback:

$(document).ready(function(){
    function_a(function(){
      function_b(); 
      function_c();
      function_d();
    });
});
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • **+1** and it's good idea to write `function_a` and how it accept a callback for making this answer better `;)`. –  Jun 04 '13 at 08:30
0

If you want to functions follow the that sequence you have to impelled Deferred. Read about jQuery .when(), .then(). jQuery is made for this.

How can jQuery deferred be used?

http://learn.jquery.com/code-organization/deferreds/examples/

or

function_a();
function_b(); 
function_c();
function_d();

Above method is also correct. But this method won't work if function_a() has asynchronous functions.

Community
  • 1
  • 1
Techie
  • 44,706
  • 42
  • 157
  • 243