I have a strange situation.
Try double clicking on “Insane” on this fiddle. You will notice that onreadystatechange is called 3 times. All these times with readyState = 4. For me, this is insane.
But the zinger is that when I remove the alert(added) from the double click event listener function as shown in this fiddle, then everything is OK.
Is there somebody who can explain to me what happened ? It is very strange for me.Thanks in advance. 🙂
This is happening because your XMLHttpRequest is set to execute asynchronously and your
alert('added')halts the JavaScript execution thread before XMLHttpRequest begins to invokeonreadystatechange. By the time you close the alert, the XMLHttpRequest has already completed and the four calls toonreadystatechangeare sitting in the stack, pending execution.Thus, because your XMLHttpRequest has already completed,
.readyStateand.statusare already equal to4and200respectively. So with each.onreadystatechangecall, yourifstatements evaluate true.If you change the XMLHttpRequest to execute synchronously (or if you place
alert('added')before invoking AJAX), then you get the number of alerts you would expect:http://jsfiddle.net/B9a5G/6/
More on JavaScript events, timing and single-threaded processing:
http://javascript.info/tutorial/events-and-timing-depth