A reaction time game sounds simple: show a signal, wait for a response, and subtract two timestamps. But what happens if someone clicks too early, holds Enter, resets a round, or switches tabs while the timer is running?
These cases are what make a JavaScript reaction time test an interesting frontend project. The challenge is not just measuring milliseconds. It is making sure each recorded score belongs to a valid round.
We’ll build a framework-free game with HTML, CSS and vanilla JavaScript, then test it with a controlled clock instead of relying on human reflexes.
1. Building a reaction time game: what can go wrong?
The happy path is simple: Start, wait for GO, respond and see a score. Real users might:
- Activate the button before the signal appears.
- Press Enter repeatedly while waiting.
- Reset the game just before the signal is due.
- Switch to another tab during a round.
- Activate the button twice in quick succession after GO.
An old timer could reveal GO during a different round, while counting early responses could make the scores misleading.
Let's define a valid round as one that starts in a visible page, reaches the GO state, receives a response in that state, and has not been interrupted. Every other active round is discarded rather than assigned an artificial penalty score.
For context, my project, Free Reaction Time Test, uses the same basic visual stimulus-and-response concept. The simplified implementation in this tutorial focuses on the underlying JavaScript logic, helping developers understand how game states, timing events and invalid responses can affect recorded scores.
2. Designing the game with four states
A state machine describes what the application is doing and which actions are allowed at that moment. We only need four states for this game.
- Idle: The player has not started a round.
- Waiting: The game is preparing to show the signal. An activation here is a false start.
- Ready: The GO signal has been requested and the next activation records a result.
- Result: A valid score or an invalid-round message is displayed. The next activation starts a new round.
Idle / Result -- start --> Waiting -- cue --> Ready
| |
early input response
| |
+---- Result ----+
Waiting / Ready -- interruption --> Result
Any state -- reset --> Idle
The key rule is that only the ready state may add a score. A second activation after a valid response may start another round, but it cannot record the previous response twice.
3. Measuring reaction time with performance.now()
Date.now() returns wall-clock milliseconds since the Unix epoch. System clock adjustments can affect it.
For elapsed time inside a browser page, performance.now() is a better fit. It uses a monotonic clock relative to the page's time origin. Its precision can still be reduced for privacy reasons.
The calculation is straightforward:
const cueTime = 2000;
const responseTime = 2250;
const elapsed = responseTime - cueTime;
console.log(elapsed); // 250 ms
These are example timestamps, not a human score. The random waiting period is excluded.
We request the cue update inside requestAnimationFrame() because the browser calls it before a repaint. This places our timestamp near the visual update, but does not prove when the pixels became visible on the monitor.
4. Handling early clicks and random delays
A fixed countdown would make it easy to predict the signal. Instead, choose a random delay between 1.5 and 4 seconds.
const delay = 1500 + Math.floor(Math.random() * 2501);
setTimeout() schedules work after a delay; it does not guarantee that the callback will execute at that exact moment. A busy JavaScript event loop can postpone it. That is why we start measuring when the cue is prepared, not when the original timeout is scheduled to expire.
We also need to cancel pending work when a round ends. clearTimeout() cancels the timer and cancelAnimationFrame() cancels the pending frame. In addition, each round receives a token. If an outdated callback somehow runs, it checks the token before touching the current state.
Native button activation also supports mouse, touch, Enter and Space without competing input handlers.
5. What happens when the user switches tabs?
Browsers may throttle timers in background pages, and animation frame callbacks are commonly paused while a page is hidden. A player returning to a hidden or unfocused game should not receive a score based on an interrupted round.
The Page Visibility API lets us observe visibility changes:
document.addEventListener('visibilitychange', () => {
if (document.hidden) game.interrupt();
});
Window blur is an extra precaution: losing focus can discard a round even if the page remains visible. Earlier valid scores are preserved.
6. Building the complete JavaScript reaction time game
Before exploring the source code, try the interactive demonstration below. Complete five valid rounds and observe how the game handles early responses, interrupted rounds and reaction time calculations.
Complete implementation
Or Save the following code as reaction-time.html and open it in your browser. No libraries, packages or build tools are needed.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Reaction time game</title>
<style>
body { font: 1rem system-ui; max-width: 36rem; margin: 3rem auto; padding: 1rem; }
#game { width: 100%; min-height: 12rem; padding: 1rem; font: inherit;
font-size: 1.4rem; color: white; background: #334155; border: 0; border-radius: .6rem; }
#game[data-state="waiting"] { background: #991b1b; }
#game[data-state="ready"] { background: #166534; }
button:focus-visible { outline: 3px solid #2563eb; outline-offset: 4px; }
</style>
<h1>Reaction time game</h1>
<p>Activate the large button to start. Wait for GO, then activate it again.</p>
<button id="game" type="button" data-state="idle">Start</button>
<p id="status" role="status">Ready to begin.</p>
<button id="reset" type="button">Reset</button>
<script>
function createGame({ now, later, clearLater, frame, clearFrame,
visible, render, random = Math.random }) {
let state = 'idle', timer = null, raf = null, token = 0;
let startedAt = 0;
const scores = [];
function show(next, label, message) {
state = next;
render({ state, label, message, scores: [...scores] });
}
function cancelPending() {
token++;
if (timer !== null) clearLater(timer);
if (raf !== null) clearFrame(raf);
timer = raf = null;
}
function interrupt() {
if (state !== 'waiting' && state !== 'ready') return;
cancelPending();
show('result', 'Try again', 'Interrupted. Round discarded.');
}
function start() {
cancelPending();
if (!visible()) {
show('result', 'Try again', 'Return to this tab first.');
return;
}
show('waiting', 'Wait...', 'Do not activate yet.');
const round = token;
const delay = 1500 + Math.floor(random() * 2501);
timer = later(() => {
if (round !== token || state !== 'waiting') return;
timer = null;
if (!visible()) return interrupt();
raf = frame(() => {
if (round !== token || state !== 'waiting') return;
raf = null;
if (!visible()) return interrupt();
startedAt = now();
show('ready', 'GO!', 'Activate now.');
});
}, delay);
}
function activate() {
if (!visible()) return interrupt();
if (state === 'waiting') {
cancelPending();
show('result', 'Try again', 'Too early. No score recorded.');
} else if (state === 'ready') {
const elapsed = now() - startedAt;
cancelPending();
scores.push(elapsed);
show('result', 'Next round', `Response: ${Math.round(elapsed)} ms`);
} else {
start();
}
}
function reset() {
cancelPending();
scores.length = 0;
show('idle', 'Start', 'Ready to begin.');
}
return { activate, interrupt, reset };
}
const button = document.querySelector('#game');
const status = document.querySelector('#status');
const game = createGame({
now: () => performance.now(),
later: (fn, ms) => setTimeout(fn, ms),
clearLater: id => clearTimeout(id),
frame: fn => requestAnimationFrame(fn),
clearFrame: id => cancelAnimationFrame(id),
visible: () => !document.hidden,
render: ({ state, label, message, scores }) => {
button.dataset.state = state;
button.textContent = label;
const sorted = [...scores].sort((a, b) => a - b);
const n = sorted.length;
const median = n ? (sorted[Math.floor((n - 1) / 2)] +
sorted[Math.floor(n / 2)]) / 2 : 0;
status.textContent = message + (n ?
` | ${n} valid | Median: ${Math.round(median)} ms` : '');
}
});
button.addEventListener('click', () => game.activate());
button.addEventListener('keydown', e => {
if (e.repeat && (e.key === 'Enter' || e.key === ' ')) e.preventDefault();
});
document.querySelector('#reset').addEventListener('click', game.reset);
document.addEventListener('visibilitychange', () => {
if (document.hidden) game.interrupt();
});
window.addEventListener('blur', game.interrupt);
</script>
</html>
createGame() receives its clock, timer, frame scheduler and rendering function as dependencies. This lets the same logic run with real browser APIs or controlled test functions.
The browser layer uses a real button, visible focus styles and text labels, so the game does not rely on color alone. The status region can announce updates to assistive technology. This is not a validated auditory reaction test: announcements may arrive later than visual changes.
We keep unrounded measurements in memory and show rounded milliseconds. The median represents the middle of the sorted scores (or the mean of the middle two for an even count), making it less sensitive to extreme values than the arithmetic mean. Reset clears all recorded scores; reloading the page also starts a fresh session.
7. Testing the game without relying on human reflexes
A person cannot reliably reproduce a response of exactly 250 ms. A controlled clock can. Open the developer console after loading the HTML example, then paste this code. It creates a separate game instance and never changes your visible game scores.
let t = 0, hidden = false, view;
let timeout, animation;
const demo = createGame({
now: () => t,
later: fn => { timeout = fn; return 1; },
clearLater: () => { timeout = null; },
frame: fn => { animation = fn; return 2; },
clearFrame: () => { animation = null; },
visible: () => !hidden,
render: next => { view = next; },
random: () => 0
});
function check(condition, label) {
if (!condition) throw new Error(label);
console.log('PASS:', label);
}
demo.activate();
const stale = timeout;
demo.activate();
stale();
check(view.state === 'result' && view.scores.length === 0,
'Early activation and stale callback');
demo.activate();
timeout();
t = 2000;
animation();
t = 2250;
demo.activate();
check(view.scores[0] === 250, 'Exactly 250 ms');
demo.activate();
check(view.state === 'waiting' && view.scores.length === 1,
'Extra activation does not duplicate the score');
hidden = true;
demo.interrupt();
check(view.state === 'result' && view.scores.length === 1,
'Hidden tab discards only the active round');
demo.reset();
check(view.state === 'idle' && view.scores.length === 0,
'Reset clears scores');
The checks cover a stale callback, a simulated 250 ms response, duplicate scoring, interruption and reset.
All five controlled checks passed when run with Node.js. Eight additional automated checks in headless Chromium also passed, including pointer and Space activation, repeated Enter suppression, reset, simulated visibility and blur events, and the absence of JavaScript page errors.
For manual testing, repeat those actions and compare the valid-score count. Actual tab switching on physical devices and cross-browser behavior still need testing.
8. Understanding the limits of browser-based measurements
A browser reaction time score is not a direct measurement of the nervous system. The display, input device, operating system, event queue and browser rendering pipeline can all affect it.
At 60 Hz, a display refresh interval is about 16.7 ms. At 144 Hz, it is about 6.9 ms. These figures describe frame intervals, not fixed amounts to subtract from a score. Display processing and the precise time a frame becomes visible can vary.
Our game measures the interval from the cue-update callback to the button activation handler. Mouse clicks typically activate on release, as does Space on a native button; Enter may activate on keydown. A press that begins before GO but is released afterward can therefore still count. If you need first-contact timing, design a separate pointerdown/keydown protocol and test it independently.
Keep the device, browser, input method and test conditions consistent when comparing runs. For precise physical timing, use appropriate external measurement equipment. A high-resolution clock alone cannot guarantee millisecond accuracy from photon to finger movement.
The lesson applies beyond reaction time games: reliable interactive software needs clear states, cancellable asynchronous work and tests for unexpected user behavior. Treat invalid measurements as invalid, rather than forcing every action into a score.
Discussion: Would you use native button activation or a separate pointerdown/keydown protocol for a browser-based response test? What trade-offs would you prioritize?
Further reading: MDN: High precision timing · MDN: setTimeout() · MDN: requestAnimationFrame() · MDN: Page Visibility API


Top comments (0)