1

I need to run 2 functions. The 2nd one must wait for the 1st one to complete otherwise things get messed up. My Code is below:

I have researched using jQuery.when() and using .then and .done but each time I try it locally I don't get it to work right as I am honestly not understanding the documentation correctly.

I have also tried to follow other questions on here which use callbacks in the function to achieve this. Again their code is slightly different and more Ajax based so hard for me to follow exactly.

I have not included my attempts of the above in the code below as it will like like a mess and will confuse. Thought it was best for question purpose clarity to show my original code with the 2 functions.

Thanks in Advance for any support...

var reportFilter = $.cookie("filter");
if (reportFilter == 'true') {
    // function 1 - Run First
    $('table tbody tr').each(function () {
        var hours = $(this).find('.time').text();
        if (hours == '0') {
            $(this).addClass('hidden');
        }
    });

    // function 2 - Run After Function 1 is complete
    $('table tbody tr').each(function () {
        var nextTR = $(this).next();
        if (nextTR.hasClass('hidden') && (nextTR.hasClass('odd') || nextTR.hasClass('even'))) {
            $(this).addClass('hidden');
        }
    });
}
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Redwall
  • 1,010
  • 5
  • 30
  • 55
  • 3
    those will run one after the other - they're not asynchronous methods. – royse41 Nov 29 '13 at 10:59
  • oh really...then I must be seeing something wrong. When I comment out the 2nd one and run the code it executes the first one. Then in Firebug I runt he 2nd one and it runs that fine and I get results. When I run as is above with both functions the results are different so I assume it was not waiting for the 1st one to finish! – Redwall Nov 29 '13 at 11:00
  • yeah something else must be going on. javascript is single threaded so code like that will always run in sequential order. async methods relate to ajax calls / timer functions etc. – royse41 Nov 29 '13 at 11:03
  • right, thanks for your help. At least I can start looking in the right place now.. damm -1 :( tough crowd.. – Redwall Nov 29 '13 at 11:06
  • 1
    +1 because this shouldn't have been voted down (in my opinion) - you had a problem, but now you've learnt something new and know where to start looking! – royse41 Nov 29 '13 at 11:23

1 Answers1

0

The two function does not seem to have any dependency. They will run in order in which they are called.

Rest to make sure that they are being called in order you want you can definitely use debugger or make alerts in function and check.

Read this link for reference:-

Wait till a Function with animations is finished until running another Function

Hope this helps!

Community
  • 1
  • 1
abhinsit
  • 3,214
  • 4
  • 21
  • 26