Is it possible to detect \"idle\" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.
Idle time:
(Partially inspired by the good core logic of Equiman earlier in this thread.)
sessionExpiration.js is lightweight yet effective and customizable. Once implemented, use in just one row:
sessionExpiration(idleMinutes, warningMinutes, logoutUrl);
This is an example of what it looks like in action, if you don't change the CSS.
I have created a small lib that does this a year ago:
https://github.com/shawnmclean/Idle.js
Description:
Tiny javascript library to report activity of user in the browser (away, idle, not looking at webpage, in a different tab, etc). that is independent of any other javascript libraries such as jquery.
Visual Studio users can get it from NuGet by: PM> Install-Package Idle.js
Here is a rough jQuery implementation of tvanfosson's idea:
$(document).ready(function(){
idleTime = 0;
//Increment the idle time counter every second.
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement()
{
idleTime++;
if (idleTime > 2)
{
doPreload();
}
}
//Zero the idle timer on mouse movement.
$(this).mousemove(function(e){
idleTime = 0;
});
function doPreload()
{
//Preload images, etc.
}
})
Here is a simple script using JQuery that handles mousemove and keypress events. If the time expires, the page reload.
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 19) { // 20 minutes
window.location.reload();
}
}
</script>
You can do it more elegantly with underscore and jquery-
$('body').on("click mousemove keyup", _.debounce(function(){
// do preload here
}, 1200000)) // 20 minutes debounce
You can use the below mentioned solution
var idleTime;
$(document).ready(function () {
reloadPage();
$('html').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
clearTimeout(idleTime);
reloadPage();
});
});
function reloadPage() {
clearTimeout(idleTime);
idleTime = setTimeout(function () {
location.reload();
}, 3000);
}