Property that is set by event handler is always displayed without change

I have a simple function that is called every second using setInterval,

I have to change the value to say if there is mouse or keyboard activity.

I update the value of my variable but it’s always set as 0 even though the console.log are called.

function generateActivity() {
    var o = { is_mouse: 0, is_keyboard: 0 };

    // Keyboard activity
    uiohook.uIOhook.on('keydown', (e) => {
        //console.log('Keyboard!')
         o.is_keyboard = 1;
    })

    // Mouse activity
    uiohook.uIOhook.on('mousemove', (e) => {
        //console.log('mouse');
        o.is_mouse = 1;
    })

    console.log(o);
}

setInterval(generateActivity, 1*1000);

>Solution :

You should set up your listeners only once, not every second — they accumulate, so this is going to give problems.

Secondly, your o object should not be created locally every second, which will give you as many objects as calls made. It should be a single object.

Something like this:

var o = { is_mouse: 0, is_keyboard: 0 };

// Keyboard activity
uiohook.uIOhook.on('keydown', (e) => {
    //console.log('Keyboard!')
     o.is_keyboard = 1;
})

// Mouse activity
uiohook.uIOhook.on('mousemove', (e) => {
    //console.log('mouse');
    o.is_mouse = 1;
})

function generateActivity() {
    console.log(JSON.stringify(o)); // Make sure the object is displayed as we want it.
    o.is_mouse = o.is_keyboard = 0; // maybe reset after logging...
}

setInterval(generateActivity, 1*1000);

Note that I have stringified the object for output, as otherwise the console may display it lazily, showing the 0 that was put in the properties after console.log was called.

Leave a Reply