Inactivity Detection
When to use it?
Detecting user inactivity is crucial for enhancing both user experience and performance optimization in modern web applications. This functionality is particularly valuable when you need to:
- Conserve resources by pausing animations, video playback, or other resource-intensive operations when users aren’t actively engaging with your site
- Enhance security by automatically logging out users after periods of inactivity
- Improve engagement by displaying targeted messages, promotions, or suggestions when users appear to be idle
- Gather analytics on user engagement patterns and session activity
- Optimize performance by deferring non-critical tasks until the browser is idle
By implementing inactivity detection, you can create more responsive applications that intelligently adapt to user behavior, leading to improved performance and more personalized user experiences.
Detection Modes
The inactivity detection supports two distinct modes:
User Idle Mode
When you provide an idleTime parameter, the system tracks user activity through events like mouse movements, scrolling, and keyboard input. The callback executes when no activity is detected for the specified duration.
Native Idle Mode
When idleTime is not provided, the system uses the browser’s requestIdleCallback API to detect when the browser is idle. This is useful for deferring non-critical work until the browser has spare time.
How To use it?
Basic Example - User Idle Mode
// Basic user inactivity detection
bstf.inactivity({
callback: () => {
console.log('User has been inactive');
document.getElementById('idle-message').style.display = 'block';
},
idleTime: 5000, // 5 seconds
name: 'basic-inactivity',
debug: true
});
Native Idle Mode Example
// Use browser's native idle detection
bstf.inactivity({
callback: () => {
console.log('Browser is idle - performing background tasks');
// Perform non-critical tasks like analytics, preloading, etc.
performBackgroundSync();
},
// No idleTime specified - uses native idle detection
maxTime: 3000, // Maximum wait time of 3 seconds
name: 'background-tasks',
debug: true
});
Example with Custom Events and Named Instance
For more control, you can specify which events to monitor and provide a name for your inactivity instance:
// Advanced inactivity detection
bstf.inactivity({
callback: () => {
// Pause video playback when user is inactive
document.querySelector('video').pause();
// Show a message
document.getElementById('activity-status').textContent = 'Inactive';
},
idleTime: 10000, // 10 seconds
events: ['mousemove', 'scroll', 'keydown', 'click', 'touchstart'],
name: 'video-player-inactivity',
debug: true
});
// Later, destroy this specific inactivity instance
document.getElementById('resume-btn').addEventListener('click', () => {
bstf.destroyinactivity({
name: 'video-player-inactivity'
});
});
Example with No Event Monitoring
You can disable event monitoring entirely by setting events: 'none'. This is useful when you only want to use native idle detection without any user activity tracking:
// Native idle detection without event monitoring
bstf.inactivity({
callback: () => {
console.log('Browser idle detected - no user events monitored');
updateCacheInBackground();
},
events: 'none', // Disable all event monitoring
maxTime: 5000,
name: 'cache-updater'
});
Example with Auto-Logout
A robust implementation of auto-logout functionality:
// Auto-logout after inactivity
const setupInactivityMonitor = () => {
bstf.inactivity({
callback: () => {
// Show a confirmation dialog
if (confirm('You have been inactive. Would you like to stay logged in?')) {
console.log('User chose to stay logged in');
// Reset the inactivity timer by destroying and recreating
bstf.destroyinactivity({ name: 'security-auto-logout' });
setupInactivityMonitor(); // Restart monitoring
} else {
// Perform logout
console.log('Logging out due to inactivity');
window.location.href = '/logout';
}
},
idleTime: 300000, // 5 minutes
maxTime: 310000, // Slightly higher than idleTime
name: 'security-auto-logout'
});
};
setupInactivityMonitor();
Configuration options
- callback
function(Required): The function to execute when the user becomes inactive or the browser is idle. - idleTime
number(Optional): Time in milliseconds to consider the user inactive. When not provided, uses native browser idle detection. Important: Must be less thanmaxTime. - maxTime
number(Optional): Maximum time in milliseconds before forcing callback execution. Defaults to 2000 (2 seconds). Acts as a safety net to ensure the callback executes. - events
array|string(Optional): Array of events to monitor for user activity, or the string'none'to disable event monitoring. Defaults to['mousemove', 'scroll', 'keydown', 'mousedown', 'mouseup', 'click', 'touchstart', 'touchend']. - name
string(Optional): Custom name for the inactivity instance. Required when destroying specific instances. - debug
boolean(Optional): Enable debug mode to see console messages. Defaults to false.
Destroying Inactivity Detection
To stop monitoring for inactivity, use the destroyinactivity method. Note that the name parameter is now required:
// Destroy a specific inactivity instance (name is required)
bstf.destroyinactivity({
name: 'my-inactivity-instance'
});
Important Constraints
-
idleTime must be less than maxTime: When using user idle mode (providing
idleTime), ensure thatidleTimeis smaller thanmaxTime. If not, the system will automatically adjustidleTimeto be 100ms less thanmaxTime. -
Name is required for destroy: Unlike previous versions, you must provide a
namewhen destroying an inactivity instance. There’s no longer an option to destroy all instances at once.
Performance Considerations
The inactivity detection uses efficient event listeners and modern browser features like requestIdleCallback when available to minimize performance impact. However, keep these best practices in mind:
- Use reasonable idle times (not too short) to avoid unnecessary callback executions
- Keep callback functions lightweight and efficient
- Consider destroying inactivity detection when it’s no longer needed
- Limit the number of events monitored to only those necessary for your use case
- Use
events: 'none'when you only need native idle detection without user activity tracking - In native idle mode, the browser determines when to execute based on available resources
Browser Compatibility
- User Idle Mode: Works in all modern browsers
- Native Idle Mode: Uses
requestIdleCallbackwhen available, falls back tosetTimeoutin older browsers - The
events: 'none'option works in all browsers but is most beneficial when combined with native idle mode
Related
- On Load Events - Defer third-party scripts
- Observer Events - Visibility-based triggers
- On Click Events - User interaction triggers
- Smart Resource Loading - Conditional loading strategies