Source Code

<div class="span-app">
  <div class="span-header">
    <h2>Digit Span</h2>
    <div class="stats">
      <div class="stat"><span class="stat-label">Level</span><span class="stat-val" id="stat-level">1</span></div>
      <div class="stat"><span class="stat-label">Lives</span><span class="stat-val" id="stat-lives">&#9679;&#9679;&#9679;</span></div>
      <div class="stat"><span class="stat-label">Best</span><span class="stat-val" id="stat-best">--</span></div>
    </div>
  </div>

  <div class="stage">
    <div class="display" id="display">Watch</div>
  </div>

  <p class="status" id="status">Memorize the sequence as it appears, one digit at a time.</p>

  <div class="entry" id="entry-wrap" hidden>
    <div class="typed" id="typed"></div>
    <div class="keypad" id="keypad"></div>
    <div class="entry-actions">
      <button id="clear-btn" class="ghost-btn">Clear</button>
      <button id="submit-btn" class="primary-btn">Submit</button>
    </div>
  </div>

  <button class="primary-btn" id="start-btn">Start game</button>
</div>

Number Sequence Memory Game — Free JS Snippet

Number Sequence Memory Game · Games · Plain HTML, CSS & JS · Live preview

What's included

Features

Sequence length grows by one digit every level, following classic digit-span test structure
Adaptive playback speed: Math.max(430, 900 - level * 35) speeds up reveal timing as levels rise
Async/await-based reveal loop built on a Promise-wrapped setTimeout sleep() helper
Dual input: an on-screen numeric keypad and physical keyboard digit keys both feed the same handler
Input guarded against accidental entry while the sequence is still animating (showing flag)
Three-life system with dot indicators; a wrong answer reveals the correct sequence before continuing
Best-level tracking compares each completed run against the session high score
Backspace and Clear controls let players fix a mistyped digit before submitting

About this UI Snippet

Number Sequence Memory Game — Digit-Span Recall with Adaptive Speed and Lives

Screenshot of the Number Sequence Memory Game snippet rendered live

A digit span test measures short-term working memory by showing a sequence of digits and asking the subject to recall it in order — the length of sequence someone can reliably reproduce is a well-known memory benchmark. This snippet turns that test into a small game: digits flash one at a time in a display panel, the sequence grows by one digit every level, playback speeds up as levels rise, and the player has three lives before the run ends.

Why this is a distinct mechanic from a color-pattern game

A game like Simon shows a spatial or color-coded pattern that the player reproduces by clicking the same colored panels back — recall there is tied to spatial/visual position memory. This game instead shows abstract digits in a single fixed location, one after another, with no spatial cues to lean on at all — the only information available is the digit's identity and its position in the sequence, which is a purer test of sequential working memory (the same skill exercised by remembering a phone number or a one-time verification code).

Building and revealing a sequence

nextRound() generates a fresh sequence of level + 2 random digits via randomDigit(), so level 1 starts at three digits and each subsequent level adds one more, following the same escalating-difficulty structure classic digit-span tests use. showSequence() is an async function that reveals the sequence one character at a time: each digit is written into displayEl.textContent, briefly gets a .flash class (scaling and brightening it for a beat), then clears before the next digit appears, all paced by await sleep(ms) calls built on a small Promise-wrapped setTimeout. The pacing itself is adaptive: Math.max(430, 900 - level * 35) shortens the per-digit reveal time as level increases, so later levels are not only longer but genuinely faster, compounding the difficulty the way real digit-span protocols do.

Numeric keypad and keyboard input working together

Once the sequence finishes playing, an on-screen numeric keypad (buildKeypad() generates ten .key buttons) and physical keyboard digit keys both feed the same onDigit() handler, which appends to a typed string only while playing is true and showing is false — guarding against accidental input while the sequence is still animating. A window.addEventListener('keydown', ...) listener mirrors every keypad action for number keys, Enter (submit), and Backspace (delete last digit), so the game is equally playable by mouse/touch or keyboard alone.

Scoring: levels, a hard three-life limit, and a persisted best

Every correct submission increments level and immediately starts the next, longer round; an incorrect submission decrements lives, reveals the correct sequence briefly in the status text so the player learns what they missed, and continues if lives remain. When lives reaches zero, endGame() stops the loop, reports the level reached, and updates best — the highest fully-cleared level — only if this run beat the previous record, giving a simple, comparable score across sessions of the same page load.

Build with AI

Build, Understand, Optimize, and Extend It With AI

Paste this snippet's HTML, CSS, and JS into an AI coding assistant like Claude and ask it to explain exactly how the async showSequence() function paces the digit reveal using the sleep() helper, and why the playback speed formula caps at a minimum of 430ms per digit rather than continuing to accelerate indefinitely. It is also a good candidate for extension — ask the assistant to add a difficulty mode using letters or a mix of letters and digits instead of only 0-9, a visual-only "flash the digit's position on a grid" variant that also tests spatial memory, or persistent best-score tracking via localStorage so a returning player has a personal record to beat across sessions.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build a digit-span memory recall game in plain HTML, CSS, and JavaScript — no libraries.

Requirements:
- On starting a level, generate a random sequence of digits whose length increases by one on every level (e.g. level 1 shows 3 digits, level 2 shows 4, and so on), and reveal it one digit at a time in a single display area using async/await-paced timing (not setInterval), with the reveal speed for each digit becoming faster at higher levels down to some reasonable minimum floor.
- After the sequence finishes revealing, present both an on-screen numeric keypad (0-9 buttons) and support physical keyboard digit key presses, both feeding into the same input-handling function, to let the player re-enter the digits in the exact order shown.
- Provide a Submit action (also triggerable with the Enter key) that compares the typed digits to the actual sequence: an exact match advances to a longer, faster next level; any mismatch consumes one of three lives and reveals what the correct sequence actually was.
- Add a Backspace/Clear way to correct mistyped digits before submitting, and disable all input while the sequence is actively being revealed so it cannot be typed over.
- Track and display the current level, remaining lives as a simple indicator, and the highest level fully cleared so far during the session. When lives reach zero, stop the game, show a game-over summary of the level reached, and offer a Play again control that resets state and starts a fresh run.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.

Step by step

How to Use

  1. 1
    Click Start gamestartGame() resets level to 1, lives to 3, and immediately calls nextRound() to generate and reveal the first sequence.
  2. 2
    Watch the sequenceDigits flash one at a time in the display panel via showSequence(). No input is accepted while showing is true, so just watch until a "?" appears.
  3. 3
    Type the sequence backUse the on-screen keypad or your physical number keys to re-enter the digits in the exact order shown. Backspace or the Clear button lets you correct a mistake before submitting.
  4. 4
    Submit and check the resultPress Submit or hit Enter. A correct match advances you to a longer, faster sequence at the next level; a wrong answer costs one life and reveals the correct sequence.
  5. 5
    Track lives and best levelThe Lives stat shows filled/empty dots for your three lives. The Best stat records the highest level you have fully cleared this session.
  6. 6
    Tune the difficulty curveAdjust level + 2 in nextRound() to change the starting sequence length, or the 900 - level * 35 formula in showSequence() to change how quickly playback speeds up per level.

Real-world uses

Common Use Cases

Working memory training and cognitive warm-ups
Digit-span recall is a standard, research-backed way to exercise short-term working memory, useful as a quick brain-training exercise distinct from spatial games like the Simon sequence game.
Daily brain-training or puzzle app widget
The level/lives/best structure gives this enough of a game loop to serve as a standalone daily challenge or mini-game inside a larger puzzle or brain-training product.
Loading-screen or waiting-room distraction
Small, self-contained and dependency-free, this drops cleanly into an idle moment in a product — a queue screen, a matchmaking wait, or an empty state — without needing a backend.
Reference for async/await-paced UI animation sequences
showSequence() is a clean, readable example of using async/await with a Promise-based sleep() helper to pace a multi-step visual reveal, reusable anywhere a UI needs a timed step-by-step animation.
Accessible dual-input pattern showcase
The shared onDigit() handler wired to both an on-screen keypad and physical keyboard events is a good reference pattern for any numeric-entry widget that needs to support touch, mouse, and keyboard equally.

Got questions?

Frequently Asked Questions

Simon-style games test spatial and color-pattern memory by having the player click the same colored panels back in order. This game shows abstract digits in a single fixed location with no spatial cues, testing pure sequential working memory instead — closer to a real digit-span cognitive test.

Two things scale together: the sequence itself grows by one digit every level (level + 2 digits), and the reveal speed accelerates via Math.max(430, 900 - level * 35), so higher levels are both longer to remember and shown to you more quickly.

endGame() is called once lives reaches zero. It stops accepting input, shows a game-over message reporting the level you reached and your best fully-cleared level for the session, and reveals the Play again button.

Yes. A window keydown listener accepts digit keys 0-9, Enter to submit, and Backspace to delete the last typed digit, mirroring every action available through the on-screen keypad.

No, best is stored in a plain JavaScript variable that resets on reload. To persist it across visits, read and write its value to localStorage inside startGame() and wherever best is updated in onSubmit().

Async/await with a Promise-wrapped setTimeout makes the multi-step reveal (show digit, flash, clear, pause, repeat) read as straightforward sequential code rather than a chain of nested callbacks or a manually tracked interval index, and makes it easy to change per-step timing based on the current level.