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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3