First of all, although it is true that javaScript is single-threaded, it is NOT true that no serialization mechanism is ever required by a javaScript application.
A simple example is that the submit button should disappear within a set period of time during which an Ajax request to the server is executed. When the asynchronous Ajax request is completed successfully, then a message should appear in which the button was.
Although it would be nice to be able to undo the fadeout button and just set your style to "display: none" once the Ajax request is complete, this is not possible in jQuery. In addition, the solution can use events to synchronize two simultaneous actions, but this is essentially redundant for a simple problem.
The low-tech solution is polling the lock, and when the fadeout completes, it unlocks, but the βserver doneβ message is NOT displayed until the success callback specified by the $ .post parameter is executed.
var gl_lock; var gl_selfID; function poll_lock(message) { if (gl_lock === 0) { $('#output').text(message).fadeIn(200); window.clearInterval(gl_selfID); } } // end of poll_lock function worker() { // no one gets in or out gl_lock = 1; $.post(..., data,function() { gl_selfID = window.setInterval(poll_lock, 40, data.message); }, "json"); // end of fadeout unlock the semaphore $('#submit-button').fadeOut(400, function() { gl_lock = 0; }); } // end of worker
Finally, I think this is a more detailed answer, as perrohunter suggested earlier in this discussion.
JackCColeman 04 Oct '15 at 0:24 2015-10-04 00:24
source share