Search code examples
javascriptmouseeventsettimeoutmousemove

Fire an event when mouse has not moved for 10 seconds


I am a bit lost where to start here. How can I fire an event when the mouse has not moved for 10 seconds? Would I need to have a resetTimer when a mouse moved, and setTimeout to 10 10 seconds? Having trouble putting it together.


Solution

  • You can use a debounced function. You can read more about debounce here

    function debounce(func, timeout) {
        let timer;
        return (...args) => {
            clearTimeout(timer);
            timer = setTimeout(() => {
                func.apply(this, args);
            }, timeout);
        };
    }
    
    const functionToRunAfterInactivity = () => {
        console.log("Mouse has not moved for 10 seconds");
    };
    
    addEventListener("mousemove", debounce(functionToRunAfterInactivity, 10000));