Most of the time you don’t really care about whether a user is actively engaged or temporarily inactive on your application. Inactive, meaning, perhaps they got up to get a drink of water, or more likely, changed tabs to do something else for a bit. There are situations, though, when tracking the user activity and detecting inactive-ness might be handy.
Let’s think about few examples when you just might need that functionality:
- tracking article reading time
- auto saving form or document
- auto pausing game
- hiding video player controls
- auto logging out users for security reasons
I recently encountered a feature that involved that last example, auto logging out inactive users for security reasons.
Why should we care about auto logout?
Many applications give users access to some amount of their personal data. Depending on the purpose of the application, the amount and the value of that data may be different. It may only be user’s name, but it may also be more sensitive data, like medical records, financial records, etc.
There are chances that some users may forget to log out and leave the session open. How many times has it happened to you? Maybe your phone suddenly rang, or you needed to leave immediately, leaving the browser on. Leaving a user session open is dangerous as someone else may use that session to extract sensitive data.
One way to fight this issue involves tracking if the user has interacted with the app within a certain period of time, then trigger logout if that time is exceeded. You may want to show a popover, or perhaps a timer that warns the user that logout is about to happen. Or you may just logout immediately when inactive user is detected.
Going one level down, what we want to do is count the time that’s passed from the user’s last interaction. If that time period is longer than our threshold, we want to fire our inactivity handler. If the user performs an action before the threshold is breached, we reset the counter and start counting again.
This article will show how we can implement such an activity tracking logic based on this example.
Step 1: Implement tracking logic
Let’s implement two functions. The first will be responsible for resetting our timer each time the user interacts with the app, and the second will handle situation when the user becomes inactive:
- resetUserActivityTimeout – This will be our method that’s responsible for clearing the existing timeout and starting a new one each time the user interacts with the application.
- inactiveUserAction – This will be our method that is fired when the user activity timeout runs out.
let userActivityTimeout = null; function resetUserActivityTimeout() { clearTimeout(userActivityTimeout); userActivityTimeout = setTimeout(() => { inactiveUserAction(); }, INACTIVE_USER_TIME_THRESHOLD); } function inactiveUserAction() { // logout logic }
OK, so we have methods responsible for tracking the activity but we do not use them anywhere yet.
Step 2: Tracking activation
Now we need to implement methods that are responsible for activating the tracking. In those methods, we add event listeners that will call our resetUserActivityTimeout method when the event is detected. You can listen on as many events as you want, but for simplicity, we will restrict that list to a few of the most common ones.
function activateActivityTracker() { window.addEventListener("mousemove", resetUserActivityTimeout); window.addEventListener("scroll", resetUserActivityTimeout); window.addEventListener("keydown", resetUserActivityTimeout); window.addEventListener("resize", resetUserActivityTimeout); }
That’s it. Our user tracking is ready. The only thing we need to do is to call the activateActivityTracker on our page load.
We can leave it like this, but if you look closer, there is a serious performance issue with the code we just committed. Each time the user interacts with the app, the whole logic runs. That’s good, but look closer. There are some types of events that are fired an enormous amount of times when the user interacts with the page, even if it isn’t necessary for our tracking. Let’s look at mousemove event. Even if you move your mouse just a touch, mousemove event will be fired dozens of times. This is a real performance killer. We can deal with that issue by introducing a throttler that will allow the user activity logic to be fired only once per specified time period.
Let’s do that now.
Step 3: Improve performance
First, we need to add one more variable that will keep reference to our throttler timeout.
let userActivityThrottlerTimeout = null
Then, we create a method that will create our throttler. In that method, we check if the throttler timeout already exists, and if it doesn’t, we create one that will fire the resetUserActivityTimeout after specific period of time. That is the period for which all user activity will not trigger the tracking logic again. After that time the throttler timeout is cleared allowing the next interaction to reset the activity tracker.
userActivityThrottler() { if (!userActivityThrottlerTimeout) { userActivityThrottlerTimeout = setTimeout(() => { resetUserActivityTimeout(); clearTimeout(userActivityThrottlerTimeout); userActivityThrottlerTimeout = null; }, USER_ACTIVITY_THROTTLER_TIME); } }
We just created a new method that should be fired on user interaction, so we need to remember to change the event handlers from resetUserActivityTimeout to userActivityThrottler in our activate logic.
activateActivityTracker() { window.addEventListener("mousemove", userActivityThrottler); // ... }
Bonus: Let’s reVue it!
Now that we have our activity tracking logic implemented let’s see how can move that logic to an application build with Vue. We will base the explanation on this example.
First we need to move all variables into our component’s data, that is the place where all reactive props live.
export default { data() { return { isInactive: false, userActivityThrottlerTimeout: null, userActivityTimeout: null }; }, // ...
Then we move all our functions to methods:
// ... methods: { activateActivityTracker() {...}, resetUserActivityTimeout() {...}, userActivityThrottler() {...}, inactiveUserAction() {...} }, // ...
Since we are using Vue and it’s reactive system, we can drop all direct DOM manipulations i.(i.e. document.getElementById("app").innerHTML) and depend on our isInactive data property. We can access the data property directly in our component’s template like below.
<template> <div> <p>User is inactive = {{ isInactive }}</p> </div> </template>
Last thing we need to do is to find a proper place to activate the tracking logic. Vue comes with component lifecycle hooks which are exactly what we need — specifically the beforeMount hook. So let’s put it there.
// ... beforeMount() { this.activateActivityTracker(); }, // ...
There is one more thing we can do. Since we are using timeouts and register event listeners on window, it is always a good practice to clean up a little bit after ourselves. We can do that in another lifecycle hook, beforeDestroy. Let’s remove all listeners that we registered and clear all timeouts when the component’s lifecycle comes to an end.
// ... beforeDestroy() { window.removeEventListener("mousemove", this.userActivityThrottler); window.removeEventListener("scroll", this.userActivityThrottler); window.removeEventListener("keydown", this.userActivityThrottler); window.removeEventListener("resize", this.userActivityThrottler); clearTimeout(this.userActivityTimeout); clearTimeout(this.userActivityThrottlerTimeout); } // ...
That’s a wrap!
This example concentrates purely on detecting user interaction with the application, reacting to it and firing a method when no interaction is detected within specific period of time. I wanted this example to be as universal as possible, so that’s why I leave the implementation of what should happened when an inactive user it detected to you.
I hope you will find this solution useful in your project!
The above is the detailed content of Detecting Inactive Users. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

TheCSSPaintingAPIenablesdynamicimagegenerationinCSSusingJavaScript.1.DeveloperscreateaPaintWorkletclasswithapaint()method.2.TheyregisteritviaregisterPaint().3.ThecustompaintfunctionisthenusedinCSSpropertieslikebackground-image.Thisallowsfordynamicvis

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

CSS,orCascadingStyleSheets,isthepartofwebdevelopmentthatcontrolsawebpage’svisualappearance,includingcolors,fonts,spacing,andlayout.Theterm“cascading”referstohowstylesareprioritized;forexample,inlinestylesoverrideexternalstyles,andspecificselectorslik
