javascript
56 lines · 8 steps
How an idle-session monitor logs you out
A class that tracks user activity across tabs and logs out after inactivity, warning first.
Explained by
highlit
1const IDLE_TIMEOUT = 15 * 60 * 1000;
2const WARNING_BEFORE = 60 * 1000;
3const ACTIVITY_EVENTS = ['mousemove', 'keydown', 'scroll', 'touchstart', 'click'];
4
5class IdleSessionMonitor {
6 constructor({ onWarn, onLogout }) {
7 this.onWarn = onWarn;
8 this.onLogout = onLogout;
9 this.idleTimer = null;
10 this.warnTimer = null;
11 this.channel = new BroadcastChannel('idle-session');
12 this.handleActivity = this.throttle(() => this.reset(true), 1000);
13 }
14
15 start() {
16 ACTIVITY_EVENTS.forEach((e) => window.addEventListener(e, this.handleActivity, { passive: true }));
17 this.channel.onmessage = ({ data }) => {
18 if (data === 'active') this.reset(false);
19 };
20 this.reset(false);
21 }
22
23 reset(broadcast) {
24 clearTimeout(this.idleTimer);
25 clearTimeout(this.warnTimer);
26 if (broadcast) this.channel.postMessage('active');
27 this.warnTimer = setTimeout(() => this.onWarn(WARNING_BEFORE), IDLE_TIMEOUT - WARNING_BEFORE);
28 this.idleTimer = setTimeout(() => this.expire(), IDLE_TIMEOUT);
29 }
30
31 async expire() {
32 this.stop();
33 await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' });
34 this.onLogout();
35 }
36
37 stop() {
38 clearTimeout(this.idleTimer);
39 clearTimeout(this.warnTimer);
40 ACTIVITY_EVENTS.forEach((e) => window.removeEventListener(e, this.handleActivity));
41 this.channel.close();
42 }
43
44 throttle(fn, wait) {
45 let last = 0;
46 return (...args) => {
47 const now = Date.now();
48 if (now - last >= wait) {
49 last = now;
50 fn(...args);
51 }
52 };
53 }
54}
55
56export default IdleSessionMonitor;
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Chained setTimeout calls that you clear and re-arm on every activity give you a clean sliding inactivity window.
- 2BroadcastChannel keeps multiple tabs of the same app in sync so activity in one tab keeps every tab alive.
- 3Throttling high-frequency events like mousemove prevents timer resets from firing on every pixel of movement.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-an-idle-session-monitor-logs-you-out-explained-javascript-f788/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.