javascript
57 lines · 10 steps
Batching analytics events in the browser
An event buffer that batches tracking calls and reliably flushes them on size, time, or page exit.
Explained by
highlit
1const MAX_BATCH_SIZE = 20;
2const FLUSH_INTERVAL = 5000;
3const ENDPOINT = '/api/analytics';
4
5class AnalyticsBuffer {
6 constructor() {
7 this.queue = [];
8 this.timer = null;
9 this.handleUnload = this.flush.bind(this, true);
10 window.addEventListener('visibilitychange', () => {
11 if (document.visibilityState === 'hidden') this.flush(true);
12 });
13 window.addEventListener('pagehide', this.handleUnload);
14 }
15
16 track(name, props = {}) {
17 this.queue.push({
18 name,
19 props,
20 ts: Date.now(),
21 url: location.pathname,
22 });
23
24 if (this.queue.length >= MAX_BATCH_SIZE) {
25 this.flush();
26 } else if (!this.timer) {
27 this.timer = setTimeout(() => this.flush(), FLUSH_INTERVAL);
28 }
29 }
30
31 flush(isUnloading = false) {
32 if (this.timer) {
33 clearTimeout(this.timer);
34 this.timer = null;
35 }
36 if (this.queue.length === 0) return;
37
38 const events = this.queue.splice(0, this.queue.length);
39 const payload = JSON.stringify({ events, sentAt: Date.now() });
40
41 if (navigator.sendBeacon) {
42 const blob = new Blob([payload], { type: 'application/json' });
43 const ok = navigator.sendBeacon(ENDPOINT, blob);
44 if (!ok) this.queue.unshift(...events);
45 return;
46 }
47
48 fetch(ENDPOINT, {
49 method: 'POST',
50 body: payload,
51 headers: { 'Content-Type': 'application/json' },
52 keepalive: isUnloading,
53 }).catch(() => this.queue.unshift(...events));
54 }
55}
56
57export const analytics = new AnalyticsBuffer();
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Batching many small events into one request cuts network overhead and server load.
- 2Page-exit events like visibilitychange and pagehide are the last chance to flush pending data.
- 3sendBeacon and keepalive fetch survive navigation where a normal request would be cancelled.
Related explainers
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
7 steps
java
@Controller public class BookController { private final BookService bookService;
Solving GraphQL N+1 with batch mapping in Spring
graphql
n+1-problem
batching
Intermediate
8 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/batching-analytics-events-in-the-browser-explained-javascript-a0b6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.