In web development, detecting idle time can be crucial for optimizing user experience. Idle time, defined as a period of user inactivity or minimal CPU usage, presents an opportunity to pre-fetch or pre-load content, reducing page load times and enhancing responsiveness.
To enable idle time detection in Vanilla JavaScript, utilize the following approach:
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 } };
Once the inactivityTime function is defined, initialize it where desired (e.g., onPageLoad):
window.onload = function() { inactivityTime(); }
You can further customize the event listeners by adding more DOM events, including:
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
Or, register events dynamically using an array:
window.addEventListener('load', resetTimer, true); var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart']; events.forEach(function(name) { document.addEventListener(name, resetTimer, true); });
Note that window.onscroll will not trigger if scrolling occurs within a scrollable element. To address this, include the third argument in window.addEventListener('scroll', resetTimer, true) to capture the event during the capture phase.
The above is the detailed content of How Can I Detect Idle Time in JavaScript to Optimize Content Pre-fetching and Pre-loading?. For more information, please follow other related articles on the PHP Chinese website!