How to Detect Idle Time in JavaScript
Read this tutorial and learn useful information about the vanilla JavaScript and jQuery solutions that are used for detecting the idle time correctly.
The idle time is the time that the user has no interaction with the web-page. It can be mouse movement, page click or when the user uses the keyboard. The idle time can be detected using vanilla JavaScript.
Vanilla JavaScript
You can use vanilla JavaScript to detect the idle time:
Vanilla JavaScript to detect the idle time
And initialize the function where you need it:
Vanilla JavaScript to detect the idle time
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<script>
let inactivityTime = function() {
let time;
window.addEventListener('load', resetTimer);
document.addEventListener('mousemove', resetTimer);
document.addEventListener('keypress', resetTimer);
function logout() {
alert("You are now logged out.")
}
function resetTimer() {
clearTimeout(time);
time = setTimeout(logout, 2000)
}
};
window.addEventListener('load', function() {
inactivityTime();
});
</script>
</body>
</html>You can also add more DOM events if it is required. The most used ones are the following:
Vanilla JavaScript to detect the idle time
To register the desired events use an array:
Vanilla JavaScript to detect the idle time
window.addEventListener('load', resetTimer, true);
let events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
events.forEach(function (name) {
document.addEventListener(name, resetTimer, true);
});DOM Events
HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document. Events collaborate with functions. The function will not be invoked before the event occurs (such as when a user clicks any button).