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
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
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
javascript
function collapseConsecutiveLogs(lines, { keyFn = (l) => l.message } = {}) { const groups = []; for (const line of lines) {
Collapsing consecutive log lines in JavaScript
grouping
run-length-encoding
data-transformation
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/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.