views:

77

answers:

2

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.');
    }
  }
}
+2  A: 

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.

eskimoblood
@eskimoblood: Very good, glad to hear that. I think what's confusing about the single-threaded nature of Javascript is that it has these asynchronous functions that in a larger sense make me think about Javascript as sort of multi-threaded, in that it has a background process that swoops in and throws callback executions into the queue, rather than everything being absolutely procedural/synchronous.
RenderIn
A: 

The rx.net team has introduced rx for javascript. Reactive extension are for asynchronous programming. they have also written for rxjs for jquery too. My be that suite your need http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx

PradeepN