Is there such a thing as an atomic test-and-set, semaphore, or lock in Javascript?
I have javascript invoking async background processes via a custom protocol (the b
First of all, while 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 when a submit button should fade out for a set amount of time during which an Ajax request to a server is working. When the asynchronous Ajax request successfully completes then a message should appear where the button used to be.
While it would be nice to be able to cancel the button's fadeout and simply set its style to "display: none", as soon as the Ajax request completes, that is not possible in jQuery. Also, a solution could use Events to synchronize the two simultaneous activities, but that is essentially overkill for a simple problem.
A low-tech solution is to poll a lock and when the fadeout completes it is unlocked but the "server done" message is NOT displayed until the success callback, as set by $.post, executes.
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 more detailed answer, along the lines previously suggested in this discussion by perrohunter.