I have a question regarding the order of execution of JavaScript (listener) methods. While I appreciate the below code is probably not best practise, is there any way to guarantee the order the below functions will fire when btn1 is changed?
$(function() {
$('#btn1').change(function(){
doStuff();
});
});
$(function() {
$(#btn1, btn2).change(function(){
doMoreStuff();
});
});
E.g. is it possible to assert that based on the order the JS code "appears in" (i.e listed in the actual js / html file), that (when #btn1 changes): 1. that doStuff() will execute first 2. that doStuff() will complete fully before doMoreStuff() is invoked – assuming all doStuff is doing is updating the DOM
I have a real example, where doStuff updates the DOM and doMoreStuff invokes an Ajax endpoint, using the updated DOM values - and want to be sure doStuff will always be invoked first (again based on the flaky design that it is "listed" first).
Thanks, Damien
As far as I'm aware, jQuery ensures event handlers fire in the order in which they were created (first in, first out). Currently I can't find any documentation on this, but I'm sure I have read that somewhere in the past.
As long as your first change
function isn't asynchronous, it should be the case that the first function will finish execution before the second starts. We can test this by adding a loop within our first change
function:
$(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>
As you can see, the first finishes before the second starts.
Collected from the Internet
Please contact debug[email protected] to delete if infringement.
Comments