Explain Codes LogoExplain Codes Logo

How to detect idle time in JavaScript

javascript
idle-detection
user-experience
performance-optimization
Anton ShumikhinbyAnton Shumikhin·Dec 24, 2024
TLDR

With a timeout initialized, and a function resetting it on user activities, you can catch a mouse on his desk vacation. Here's the essence:

let idleTimer; const resetIdleTimer = () => { clearTimeout(idleTimer); // swing the magic wand - time reset! idleTimer = setTimeout(() => console.log('User is vacationing on the moon'), 5000); // makes a note after 5 seconds }; ['mousemove', 'keypress'].forEach(ev => document.addEventListener(ev, resetIdleTimer)); // create an army of spies 🕵️‍♀️🕵️ for user actions resetIdleTimer(); // wake up the spies

The browser starts a 5-second countdown every time the user is active. If they take a coffee break, the setTimeout completes, logs the idle message while the user sips away. We keep the espresso machine running on any mouse or key movement.

Exploiting idle time

Idle detection is more than just spying on mouse movements and keypresses. It's about commoditizing user inactivity. This can lead to optimizing user experience and providing smooth and uninterrupted service. Below I discuss a few strategies:

  1. Pre-fetching content: Load heavy content while the user is idle, ensuring a seamless experience on user's return.

  2. Page load monitoring: Always initialize your idle timer at page load for real-time data.

  3. Comprehensive event tracking: Track other user events like scroll and click alongside mousemove and keypress.

  4. Handling resource-intensive applications: Use idle times to perform heavy tasks in your app, allowing for optimized CPU usage.

  5. Use reliable libraries: If building from scratch is not an option, Idle.js is there to share your burden.

window.addEventListener('scroll', resetIdleTimer, { capture: true, passive: true }); // the super spy - handles even scrolling!

In the command above, using the capture phase in an addEventListener gives an early warning system for your idle detection.

Perfecting your idle detection strategy

Handling events uniformly across browsers

Pick between plain JavaScript or jQuery depending on how severe your browser compatibility phobia is! Always use responsive code to adapt to different browser's event management systems.

Improving pre-fetched content usability

Feeling generous with your preloaded content might cause you heavy data bills! Ensure an optimal preloading strategy by considering the user experience and the relevance of the pre-fetched content.

Analyzing user presence

The Page Visibility API helps with understanding if your application is a regular joe or a "most wanted" tab in the user's browser. Your application needs a different strategy for both scenarios.

In the end, detecting user idle time should not only be about optimizing resources, but also should serve the ulterior motive of enhancing user engagement.