Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading