How to Detect Idle Time in JavaScript ?
Last Updated :
24 Jan, 2023
The idle time is the time that the user doesn't interact with a web page. This interaction can be either moving the mouse, clicking on the page, or using the keyboard. This time can be detected to execute certain events that may need to occur after a certain period of idle time. \
Method 1: Using JavaScript: For the implementation, two functions are created, one is the function that resets the timer whenever user interaction is detected and the other is the function that would be executed periodically during the time the user is idle. The reset function consists of the setInterval() function, which is used to create a new interval that will repeatedly invoke another function. The timer created is assigned to a variable that will be used to clear out the old timer whenever this function is called again on user interaction.
This function is invoked by binding it to the events that cause interaction with the page. These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress.
The other function which will be invoked when the user is idle can be used to keep track of the time and perform actions when the user has been inactive for a longer time. An example of this would be to log out the user when inactive for more than a specified time.
Example:
html
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<b>
How to detect idle time in
JavaScript elegantly?
</b>
<p>
The timer will be incremented every
second to denote the idle time.
Interaction with the mouse or
keyboard will reset and hide the timer.
</p>
<p class="timertext" style="font-size: 1.5rem;">
You are idle for
<span class="secs"></span> seconds.
</p>
<script type="text/javascript">
let timer, currSeconds = 0;
function resetTimer() {
/* Hide the timer text */
document.querySelector(".timertext")
.style.display = 'none';
/* Clear the previous interval */
clearInterval(timer);
/* Reset the seconds of the timer */
currSeconds = 0;
/* Set a new interval */
timer =
setInterval(startIdleTimer, 1000);
}
// Define the events that
// would reset the timer
window.onload = resetTimer;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer;
window.ontouchstart = resetTimer;
window.onclick = resetTimer;
window.onkeypress = resetTimer;
function startIdleTimer() {
/* Increment the
timer seconds */
currSeconds++;
/* Set the timer text
to the new value */
document.querySelector(".secs")
.textContent = currSeconds;
/* Display the timer text */
document.querySelector(".timertext")
.style.display = 'block';
}
</script>
</body>
Output:
How to Detect Idle Time in JavaScript ?
Method 2: Using jQuery: It similar to the above method, however here a new timer is not created every time when user interaction is detected. Instead, the running timer is reset to 0 whenever user interaction is detected. For the implementation, two functions are created, one is the function that resets the timer to 0 whenever user interaction is detected and the other is the function that would be executed periodically during the time the user is idle. A new variable is defined which will globally represent the current time of the idle timer.
Using the document.ready() event, a timer with the setInterval() function is created which repeatedly invokes another function that handles what will happen when the user is idle for a specified time. The reset function consists of a simple statement that will change the value of the timer variable to 0, effectively resetting the current idle time. This function is invoked by binding it to the events that cause interaction to the page. These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress.
Example:
html
<head>
<script src=
"https://code.jquery.com/jquery-3.4.1.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to detect idle time in
JavaScript elegantly?
</b>
<p>
The timer will be incremented every
second to denote the idle time.
Interaction with the mouse or keyboard
will reset and hide the timer.
</p>
<p class="timertext" style="font-size: 1.5rem;">
You are idle for
<span class="secs"></span> seconds.
</p>
<script type="text/javascript">
var currSeconds = 0;
$(document).ready(function() {
/* Increment the idle time
counter every second */
let idleInterval =
setInterval(timerIncrement, 1000);
/* Zero the idle timer
on mouse movement */
$(this).mousemove(resetTimer);
$(this).keypress(resetTimer);
});
function resetTimer() {
/* Hide the timer text */
document.querySelector(".timertext")
.style.display = 'none';
currSeconds = 0;
}
function timerIncrement() {
currSeconds = currSeconds + 1;
/* Set the timer text to
the new value */
document.querySelector(".secs")
.textContent = currSeconds;
/* Display the timer text */
document.querySelector(".timertext")
.style.display = 'block';
}
</script>
</body>
Output:
How to Detect Idle Time in JavaScript?
Similar Reads
How to Get Current Time in JavaScript ? This article will show you how to get the current time in JavaScript. Whether you are creating a digital clock, scheduling events, or simply logging timestamps, knowing how to retrieve the current time is essential. Here, we will cover different methods to get the current time in JavaScript.Table of
2 min read
How to Set Time Delay in JavaScript? Delaying the execution of code is a fundamental technique that is commonly used in JavaScript for tasks like animations, API polling, or managing time intervals between actions. JavaScript provides several built-in methods to set time delays: setTimeout() and setInterval(). We can set time delay in
2 min read
How to Get Milliseconds in JavaScript? In JavaScript, you can get the current time in milliseconds, which is useful for timestamping events, measuring time intervals, and performing time calculations. JavaScript provides various methods to precisely measure time down to the millisecond, including Date.now(), performance.now(), and the Da
2 min read
JavaScript - How To Create A Countdown Timer? A countdown timer is a timer that runs for a specific time limit and when that limit get crossed then it stops the timer and the message get displayed on the screen. it can be used for a website or blog to display the countdown to any special event, such as a birthday or anniversary.The Basics of a
4 min read
How to get the client timezone offset in JavaScript? The client's timezone offset could be detected by using the Date object's getTimezoneOffset() method. The getTimezoneOffset() method returns the time difference between UTC time and local time, that is the time offset, in minutes. This offset is changed by dividing by 60 and negating the result. Not
1 min read