Home >Web Front-end >JS Tutorial >How Can I Detect User Idle Time in JavaScript?
Detecting Idle Time in JavaScript
Introduction:
In web development, understanding user activity is crucial for optimizing performance and providing a better user experience. Detecting idle time, defined as a period of inactivity or low CPU usage, can help you trigger actions like preloading content or user authentication.
JavaScript Implementation:
To detect idle time in JavaScript, you can utilize the following vanilla JavaScript approach:
Code Snippet:
var inactivityTime = function () { var time; window.onload = resetTimer; // DOM Events document.onmousemove = resetTimer; document.onkeydown = resetTimer; function logout() { alert("You are now logged out.") //location.href = 'logout.html' } function resetTimer() { clearTimeout(time); time = setTimeout(logout, 3000) // 1000 milliseconds = 1 second } };
Usage:
To initialize idle time detection, call the inactivityTime() function after the page has loaded:
window.onload = function() { inactivityTime(); }
Customization:
You can add more DOM events to monitor user activity. Some of the most commonly used events are:
document.onload = resetTimer; document.onmousemove = resetTimer; document.onmousedown = resetTimer; // touchscreen presses document.ontouchstart = resetTimer; document.onclick = resetTimer; // touchpad clicks document.onkeydown = resetTimer; // onkeypress is deprectaed document.addEventListener('scroll', resetTimer, true); // improved; see comments
For better customization, you can use an array to register multiple events:
window.addEventListener('load', resetTimer, true); var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart']; events.forEach(function(name) { document.addEventListener(name, resetTimer, true); });
By customizing the events you monitor, you can tailor idle time detection to fit your specific application's needs.
The above is the detailed content of How Can I Detect User Idle Time in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!