Home > Software design >  How to track an inactive mouse once a page loads?
How to track an inactive mouse once a page loads?

Time:01-11

Right now, I have a function set up to do something if a mouse is inactive for 10 seconds for mobile only. However my console.log doesn't appear unless there is some activity before it is triggered by the inactivity. here is my code:

    if (width <= 480) {
       const inactiveUserMessage = () => {
             console.log("mouse has been inactive for 10 seconds");
       };
       document.addEventListener("mousemove", debounce(inactiveUserMessage, 10000));
    }
    

***In another file, lives the debounce function:

export function debounce(func, timeout) {
    let timer;
    return (...args) => {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func.apply(this, args);
        }, timeout);
    };
}

There needs to be some kind of activity before the inactiveUserMessage triggers. However how do i do it where the debounce function runs right away without needing some kind of movement before?? Please help!!!

Please let me know if this makes sense or if you need some more information.

I tried to create a mousemove event listener with a debounce function but it doesn't work unless there is some kind of movement on the page before hand.

I tried to create a mousemove event listener with a debounce function but it doesn't work unless there is some kind of movement on the page before hand.

CodePudding user response:

Use the window's "load" event to start the timer and pass the timer to the debounce function. Something like this;

let timer;
const inactiveUserMessage = () => {
     console.log("mouse has been inactive for 10 seconds");
};

window.addEventListener("load", () => {
     timer = setTimeout(inactiveUserMessage, 10000);
});

...

if (width <= 480) {
    document.addEventListener("mousemove", debounce(inactiveUserMessage, 10000), timer);
}
...
export function debounce(func, timeout, timer) {
    return (...args) => {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func.apply(this, args);
        }, timeout);
    };
}
  • Related