I have a function which is an event handler for websocket.onmessage
, now since the server can send multiple messages (one after another) and each message will trigger that event, and since the function block may take a few seconds (a lot of rendering going on inside), the function may be called again while the first function call is still running.
I need a critical block in this function in some cases so that the second call will only start the critical section when the first call ends, what's considered a 'best practice' for implementing locks in JavaScript?
JavaScript Event Handlers Event handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.
Since js is single-threaded, you can't really do locks. Well, you can but you shouldn't.
One idea might be to keep a status variable.
Your function will be called on each onmessage, but you only do something if the variable is set to false. If so, you set it to true and when its done, set it back to false.
var handler; //expose outside the closure
(function(){
var busy = false;
handler = function(){
if( !busy ){
busy = true;
//do rendering stuff
busy = false;
}
}
})();
Obviously, adapt this idea to your own needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With