I guess you could do it like that. You can get the total time it took from the getIdleTime
method, and if you want to track some more events, you could do that through the actionsToTrack
const
function TimeKeeper(selector) {
const timeKeeper = document.querySelector(selector);
const actionsToTrack = ['mousemove', 'mouseenter', 'mouseleave', 'keyup', 'keydown', 'keypress'];
let lastMoveTime = new Date();
let idleTime = 0;
// this updates the time and updates the element showing the inactive time
let update = (newTime) => {
idleTime += newTime;
timeKeeper.innerHTML = `${idleTime} ms`;
};
// will execute for every different kind of action
// you could potentially log the action to see if it got caught or not
const trackAction = (action) => function() {
lastMoveTime = new Date();
};
setInterval(() => {
let moveTime = new Date();
let diff = moveTime - lastMoveTime;
// i don't see 100 ms of inactivity necessarily as idle, but okay
if (diff >= 100) {
update(diff);
lastMoveTime = moveTime;
}
}, 100);
// attaches the handlers
Object.keys( actionsToTrack ).forEach(action =>
document.body.addEventListener(actionsToTrack[action], trackAction( actionsToTrack[action] ) )
);
// returns the idle time
this.getIdleTime = () => {
return idleTime;
};
// resets the idle time
this.reset = () => {
idleTime = 0;
};
}
var tk = new TimeKeeper('#idleTime');
html,
body {
position: absolute;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
.timekeeper {
position: absolute;
top: 0;
right: 0;
}
<div id="idleTime" class="timekeeper"></div>
Note that for a mousemove, the cursor has to pass the body itself, since I don't have any content i just stretched it...