We wanted an activity monitor to force logging off authenticated users after a certain period of inactivity. So naturally we searched the web to see how others implemented similar solutions. The prominent AI summary suggested the following, which we initially implemented.
<script>
let inactivityTimeout;
// Function to log the user out
function logOut() {
alert("You have been logged out due to inactivity.");
// Redirect to a logout page or perform logout logic
window.location.href = "/logout";
}
// Reset the inactivity timer
function resetTimer() {
clearTimeout(inactivityTimeout);
inactivityTimeout = setTimeout(logOut, 5 * 60 * 1000); // 5 minutes
}
// Add event listeners for user activity
function setupInactivityTimer() {
document.addEventListener("mousemove", resetTimer);
document.addEventListener("keydown", resetTimer);
document.addEventListener("click", resetTimer);
document.addEventListener("scroll", resetTimer);
resetTimer(); // Start the timer initially
}
// Initialize the inactivity timer when the page loads
window.onload = setupInactivityTimer;
</script>
While that gets the job done, the constant recycling of inactivityTimeout
struck us as grossly inefficient. Considering how many times those events are triggered while interacting with pages, it was determined a poor solution.
We instead decided to use a Date
variable, updated as each event is triggered, and monitored in reasonable intervals. This example below shows how we check that variable once a minute, determine if more than 10 minutes have passed since last activity, and automatically log out.