In my ASP.Net boilerplate application I want to write an efficient (efficient in terms of performance) javascript code that would allow me to track user activity an a given page including the time at which the user entered the page and the time at which left the page.
To track the user activity I ended up with this code:
function activityWatcher() {
//The number of seconds that have passed since the user was active.
var secondsSinceLastActivity = 0;
//in secs
var maxInactivity = 30;
//Setup the setInterval method to run every second. 1000 milliseconds = 1 second.
setInterval(function () {
secondsSinceLastActivity++;
console.log(secondsSinceLastActivity + ' seconds since the user was last active');
//if the user has been inactive or idle for longer then the seconds specified in maxInactivity
if (secondsSinceLastActivity > maxInactivity) {
console.log('User has been inactive for more than ' + maxInactivity + ' seconds');
}
}, 1000);
//The function that will be called whenever a user is active
function activity() {
//reset the secondsSinceLastActivity variable back to 0
secondsSinceLastActivity = 0;
}
//An array of DOM events that should be interpreted as user activity.
var activityEvents = ['mousedown', 'mousemove', 'keydown','scroll', 'touchstart'];
//add these events to the document & register the activity function as the listener parameter.
activityEvents.forEach(function (eventName) {
document.addEventListener(eventName, activity, true);
});
}
activityWatcher();
This code does the job really well but I have a couple of questions.
-Is this code efficient performance wise or is there a way to make its performance better?
-I'm stuck on how to get the time at which the user entered the page and the time at which the user left the page.
-Lets say I want to save some information (like the time the user entered & left the page etc...) to the database, how to save those info to the db in a performant way?