Of course! Here is a complete, self-contained website that checks reaction time according to your specifications.
You can copy and paste this code into a single index.html file and open it in any web browser to use it.
The Complete Code (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reaction Time Test</title>
<style>
/* Basic CSS for a clean look */
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
overflow: hidden; /* Prevents scrollbars */
}
/* The main game area that fills the screen */
#game-area {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
width: 100vw;
height: 100vh;
color: white;
text-align: center;
transition: background-color 0.15s ease-in-out;
cursor: pointer; /* Indicates it's interactive */
}
/* Text styling for better readability */
#message {
font-size: 3rem;
font-weight: bold;
text-shadow: 2px 2px 8px rgba(0,0,0,0.5);
}
#result {
font-size: 1.5rem;
margin-top: 20px;
}
/* --- STATE COLORS --- */
/* Initial state: Ready to start */
.state-ready {
background-color: #3498db; /* Blue */
}
/* Waiting state: User is holding the key */
.state-wait {
background-color: #e74c3c; /* Red */
}
/* Go state: Time to react! */
.state-go {
background-color: #2ecc71; /* Green */
}
/* Too Soon state: User released the key too early */
.state-too-soon {
background-color: #f1c40f; /* Yellow */
}
</style>
</head>
<body>
<div id="game-area" class="state-ready">
<h1 id="message">Hold the Enter key to begin</h1>
<p id="result"></p>
</div>
<script>
// --- DOM Elements ---
const gameArea = document.getElementById('game-area');
const message = document.getElementById('message');
const result = document.getElementById('result');
// --- Game State Variables ---
let gameState = 'ready'; // 'ready', 'wait', 'go', 'too-soon'
let timerTimeout; // Stores the timeout for the color change
let startTime; // Stores the timestamp when the screen turns green
// --- Event Listeners ---
// We need to listen for when a key is pressed down and when it's released.
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
// Also add mouse/touch controls for mobile friendliness
gameArea.addEventListener('mousedown', handleKeyDown);
gameArea.addEventListener('touchstart', handleKeyDown);
gameArea.addEventListener('mouseup', handleKeyUp);
gameArea.addEventListener('touchend', handleKeyUp);
// --- Event Handler Functions ---
/**
* Handles the 'keydown' or 'mousedown' event.
* This function starts the "waiting" phase.
*/
function handleKeyDown(event) {
// Check if the key is Enter or if it's a mouse/touch event.
// Also, only proceed if we are in a state that allows starting a new game.
// The `gameState === 'wait'` check prevents the timer from restarting if the user holds Enter.
if ((event.key === 'Enter' || event.type === 'mousedown' || event.type === 'touchstart') && (gameState === 'ready' || gameState === 'too-soon')) {
// Prevent default browser actions (like form submission on Enter)
event.preventDefault();
// 1. Change to the "wait" state
gameState = 'wait';
updateUI();
// 2. Set a random timer to change to the "go" state
// This makes the test unpredictable. The delay is between 2 and 5 seconds.
const randomDelay = Math.random() * 3000 + 2000;
timerTimeout = setTimeout(() => {
// When the timer finishes, change to the "go" state
gameState = 'go';
// Record the exact start time for the reaction measurement
startTime = performance.now();
updateUI();
}, randomDelay);
}
}
/**
* Handles the 'keyup' or 'mouseup' event.
* This function either stops the test or flags a "too soon" attempt.
*/
function handleKeyUp(event) {
// Check if the key is Enter or if it's a mouse/touch event.
if (event.key === 'Enter' || event.type === 'mouseup' || event.type === 'touchend') {
event.preventDefault();
// Case 1: The user released too soon (while the screen was red)
if (gameState === 'wait') {
clearTimeout(timerTimeout); // IMPORTANT: Cancel the pending 'go' state change
gameState = 'too-soon';
updateUI();
}
// Case 2: The user reacted correctly (released after screen turned green)
else if (gameState === 'go') {
const endTime = performance.now();
const reactionTime = Math.round(endTime - startTime);
// Display the result and reset to the 'ready' state
gameState = 'ready';
updateUI(reactionTime);
}
}
}
/**
* A helper function to update the screen's text and color based on the current gameState.
* This keeps the code clean and organized.
*/
function updateUI(reactionTime = null) {
result.textContent = ''; // Clear previous results by default
switch (gameState) {
case 'ready':
gameArea.className = 'state-ready';
message.textContent = 'Hold Enter to Begin';
if (reactionTime) {
result.textContent = `Your time: ${reactionTime} ms. Hold Enter to try again.`;
}
break;
case 'wait':
gameArea.className = 'state-wait';
message.textContent = '...Wait for Green...';
break;
case 'go':
gameArea.className = 'state-go';
message.textContent = 'RELEASE!';
break;
case 'too-soon':
gameArea.className = 'state-too-soon';
message.textContent = 'Too Soon!';
result.textContent = 'Release AFTER the screen turns green. Hold Enter to try again.';
break;
}
}
</script>
</body>
</html>
How It Works: A Breakdown
1. HTML Structure
- A single
<div id="game-area"> acts as the main container. Its background color will change to signal the user.
- Inside it, an
<h1 id="message"> displays the primary instruction (e.g., "Wait for Green", "RELEASE!").
- A
<p id="result"> is used to show the final reaction time or error messages.
2. CSS Styling
- The
body, html, and #game-area are styled to fill the entire browser window. display: flex is used to perfectly center the text.
- The core of the visual feedback is the
state-* classes:
.state-ready: A neutral blue color for the starting screen.
.state-wait: A red "hold" color to build anticipation.
.state-go: The green "release now!" signal.
.state-too-soon: A yellow "error" color if the user releases the key prematurely.
- A
transition on the background-color makes the color changes a little smoother.
3. JavaScript Logic (The Core Engine)
-
State Management: The entire game is controlled by a single variable, gameState. It can be 'ready', 'wait', 'go', or 'too-soon'. Every user action checks this variable to decide what to do next.
-
Event Listeners:
keydown / mousedown: Listens for when the user presses and holds the "Enter" key or mouse button.
keyup / mouseup: Listens for when the user releases the key/button.
- This "down" and "up" distinction is crucial for the "hold-and-release" mechanic.
- We added mouse and touch events to make it work on mobile phones and for users who prefer the mouse.
-
Game Flow:
- Start (
ready state): The page loads. The user is told to "Hold Enter".
- User Holds Key (
handleKeyDown):
- The state changes to
wait.
- The screen turns red, and the message changes to "Wait for Green".
- A
setTimeout is created with a random delay (between 2-5 seconds). This prevents users from just guessing the timing.
- The Wait:
- Scenario A (Success): The random timer finishes. The
setTimeout function runs, changing the state to go. The screen turns green, and we immediately record the startTime using performance.now() for high precision.
- Scenario B (Failure): The user releases the key before the screen turns green. The
handleKeyUp function sees that the state is still wait, flags it as "Too Soon", and crucially, calls clearTimeout() to cancel the timer that would have turned the screen green. The state becomes too-soon.
- User Releases Key (
handleKeyUp):
- If the state is
go (meaning the screen was green), this is a successful attempt.
- It records the
endTime, calculates the reactionTime, and updates the UI to show the result.
- The game state is reset to
ready so the user can play again.