There are no semaphores or critical sections because JavaScript is single-threaded. The ajax call you make is asynchronous, so it starts the request, and then happily keeps going and leaves your critical section. As others have noted, a simple solution is to make the request synchronous, but that defeats the goal of ajax.
By looking at your code, it seems like you are trying to get updates at regular intervals. If so, why not plan the next update in the ajax request callback?
this.getMessages = function (){ var url="getmessages.php?lastindex="+this.lastindex; $.getJSON(url, function(data){ gup.lastindex=data.lastindex; $.each(data.updates, function(i,item){ gup.addUpdate(item); }); gup.updateTimer=setTimeout(gup.getMessages, 30); } ); }
This eliminates the need for semaphores and is more consistent with the nature of JavaScript caused by events. The disadvantage is that updates are not performed at exact intervals. In addition, 30 milliseconds seems to be an extremely short interval.
seelmobile
source share