Skip to content
Advertisement

Is there any possibility of two asynchronous Javascript function instances executing two blocks of code at the same time?

I understand that Javascript doesn’t have multiple threads, but I’d like to know if the following code has any chance of breaking. My understanding is that unless an asynchronous function is called, such as setTimeout or an AJAX call, that once a block of code starts executing there’s no way for it to pause until it completes or does call an asynchronous function.

Basically, users select multiple checkboxes and then hits a button that executes AJAX processing of their selections. My goal is to have a “Saving…” icon that stays only until all the AJAX processes are complete, and after all are finished display a success message.

Barring any AJAX errors, so long as the callback function in the jQuery.post executes in its entirety without interruption, I don’t see how the if(numProcessed == toProcess) would ever execute more than once or less than once. But if two AJAX callbacks get into the callback function, both increment the numProcessed counter before either get to the following if, then it seems that the code inside would be executed twice.

var numProcessed = 0;
var checkedBoxes = jQuery("input[type=checkbox]:checked");
var toProcess = checkedBoxes.size();

checkedBoxes.each(function() {
  jQuery.post('somepage.php',{...},function(results) {
    numProcessed++;
    if(numProcessed == toProcess) {
      jQuery("#saving-message").remove();
      jQuery("#feedback-panel").text('Successfully processed all selections.');
    }
  }
}

Advertisement

Answer

There is only one thread in JavaScript so every function that want to be execute is put in stack and have to wait until all others are execute. In your case “each” is the first function in the stack, so every callback function have to wait and will be execute in the order they put on the stack. After all “numProcessed == toProcess” could only one time be true.

Advertisement