Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript synchronization and critical sections in event handlers

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?

like image 249
Mikey S. Avatar asked Sep 21 '12 19:09

Mikey S.


People also ask

What is the purpose of the event handlers in the 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.


1 Answers

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.

like image 66
Geuis Avatar answered Oct 28 '22 17:10

Geuis