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
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
Intermediate
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.