JavaScript listener execution order

I have a question about JavaScript execution order (listeners). While I appreciate that the code below is probably not the best way, is there a way to ensure that the following functions fire in order when btn1 changes?

  $(function() {
    $('#btn1').change(function(){
            doStuff();
    });
  });

  $(function() {
    $(#btn1, btn2).change(function(){
            doMoreStuff();
    });
  });

      

eg. it could be argued that based on the order in which the JS code appears "(which is specified in the actual js / html file) (when # btn1 changes): 1. that doStuff () will execute first 2. that doStuff () will complete completely before doMoreStuff () call - all doStuffs are assumed to be doing DOM updates

I have a real-world example where doStuff updates the DOM and doMoreStuff calls the Ajax endpoint using the updated DOM values ​​- and I want to make sure that makeStuff will always be called first (again based on the flaky design it "specified" "first) ...

Thanks, Damien

+3


source to share


1 answer


As far as I know, jQuery handles event handlers in the order they were created (first in, first). I can't find any documentation on this at this time, but I'm sure I read this somewhere in the past.

As long as your first function is change

not asynchronous, it should be so that the first function will finish executing before starting the second run. We can test this by adding a loop to our first function change

:



$(function() {
  $('#btn1').change(function(){
    console.log("First change event triggered at " + +(new Date()));
    
    for (var i = 0; i < 100000000; i++)
      continue;
    
    console.log("First change event finished at " + +(new Date()));
  });
});

$(function() {
  $('#btn1, #btn2').change(function(){
    console.log("Second change event triggered at " + +(new Date()));
  });
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="btn1"><option>1</option><option>2</option></select>
<select id="btn2"><option>1</option><option>2</option></select>
      

Run codeHide result


As you can see, the first one ends before the second launch starts.

+3


source







All Articles