Menu Item Callback and Keyboard Event Handler callback the same section of code

Hello,
I have an issue where the menu item callback and the keyboard event callback need to call the same piece of code. However, only one should execute if both are press simultaneously(or close). It does not matter which one wins, but only one can win. I tried making a test and set with a lock. However that does not seem to work. If I click the menu item then wait like a second and press keyboard it works fine. The second one does not execute. I found through print statements that the lock is true for both events when fired close together, but since it it JS this should not occur because it is single threaded. In theory it should give lock only to one. Any insight as to why the lock is not being given to only one caller. My lock code is as follows:

    testAndSetEventBeingHandled: function(lock) {
        var intial = lock;
        this.isHandlingEvent = true;
        return intial;
    }

    .......
    testFunction: function() {
        if(this.testAndSetEventBeingHandled(this.isHandlingEvent))
             return
        ... enter critical section and do some stuff ....
        this.isHandlingEvent = false;
    }

Thank you,

Hi, @ericc

I don’t think your lock will work. Javascript runtime is a single thread process, so even the click event on menu item and your keyboard event is triggered at the exact same time, the testFunction will be executed two time in a roll. So this.testAndSetEventBeingHandled(this.isHandlingEvent) will always return false.

You can have a lock which unlock just a few ms later

    unlockEvent: function() {
        this.isHandlingEvent = false;
    },
    testFunction: function() {
        if(this.isHandlingEvent)
             return;
        // ... enter critical section and do some stuff ....
        this.isHandlingEvent = true;
        this.scheduleOnce(unlockEvent, 0.01); // 10 ms
    }

Note that scheduleOnce is a function of cc.Node, you can have such code functioning only in a class inherit from cc.Node (can be indirect).

Huabin

Thank you. I think that worked