Skip to content
Tutorials Center
My learning

Topics

Lesson 127 of 156 · Projects

Project: Quiz Game

Build a timed quiz game in plain JavaScript, step by step - screens driven by state, answer checking, scoring, a countdown timer, results and keyboard play.

In this project you'll build a quiz game: a start screen, a series of multiple-choice questions with a countdown, instant feedback, a score that rewards fast answers and a results screen that reviews every question. It's a fun thing to make, and it teaches a skill every interface needs: moving between screens while keeping the data behind them in order.

The To-Do App project introduced the state, then render idea for a single list. A quiz pushes that idea further. The app now has a current screen, a position in the question list, a score, a chosen answer and a timer that keeps ticking while the user thinks. You'll see how to keep all of that under control.

You'll build the game in six stages. Each stage is a complete, runnable example that adds one feature, and the last stage is the finished game.

What you'll build

The finished game:

  • shows a start screen, then six questions, then a results screen;
  • gives each question a 15-second countdown with a shrinking bar;
  • marks the chosen answer right or wrong, highlights the correct one and explains it;
  • awards 100 points for a correct answer plus a speed bonus of up to 50;
  • reviews every answer at the end, shuffles the questions each round and remembers your best score for the session;
  • can be played entirely with the keyboard: 1–4 to answer, Enter to continue.

It uses ideas from these lessons: Objects, Arrays, map, filter, reduce and forEach, Creating and Removing Elements, Bubbling, Capturing and Delegation, setTimeout and setInterval and The Math Object.

Step 1: Three screens in HTML and CSS

A quiz has three screens. Each one is a <section> inside the same page; later, JavaScript will show exactly one of them at a time. For now all three are visible with sample content, so you can check the design before any logic exists.

Step 1: The three screens

The option buttons have type="button" and live in a <div>, not a form, because nothing is submitted. Real buttons matter: they can be focused with Tab, pressed with Enter or Space and announced by screen readers, all for free. The .correct and .wrong classes and the .low timer class are ready for JavaScript to switch on.

Step 2: Questions, state and screens

Now for the data. Each question is an object with the question text, a list of options, the index of the right answer (counting from 0, as arrays do) and an explanation shown after answering.

The state of the game starts small: which screen is visible and the index of the current question. A single render() function reads the state and updates the page:

  • It shows one section and hides the others with the hidden property.
  • On the question screen, it builds one button per option with createElement() and textContent.

Event handlers only change the state and call render(). In this step there's no answering yet: a Skip button walks through the questions so you can check that every one renders.

Step 2: Render screens from state

render() is the only function that touches what the user sees, and it does so purely from state. Notice that startQuiz() replaces state with a brand-new object instead of patching the old one. That makes it impossible for a leftover value from the previous round to sneak into the next one.

Each option button stores its position in data-index, so a click handler can later find out which option was chosen without one listener per button.

Step 3: Answering and scoring

The state now needs to remember three more things:

  • score: the running total.
  • picked: the option chosen for the current question, or null while the user is still deciding.
  • answers: one record per question, used for the results screen.

One click listener on the options container handles every option, using event delegation and closest(). Because render() replaces the buttons for every question, listeners on the buttons themselves would be lost each time; the container stays put.

When picked is not null, renderQuestion() disables the buttons, colors the right and wrong options, writes the feedback and reveals the Next button.

Step 3: Pick answers and keep score

The first line of choose() is a guard clause. Once a question is answered, any further clicks are ignored, even if a button were somehow still enabled. Guards like this matter more and more as you add ways to trigger the same action, such as a timer and keyboard shortcuts.

data-index is a string, so the listener converts it with Number() before comparing it to current.answer. With ===, "1" === 1 would be false and every answer would look wrong.

Step 4: A countdown timer

Each question now gets 15 seconds. The timer is the trickiest part of the game, for two reasons.

First, setInterval isn't precise. Browsers can delay timers, especially in background tabs, so counting "one tick = one second" slowly drifts. Instead, save a deadline when the question appears and, on every tick, calculate the time left from the clock with performance.now(). Ticking every 200 milliseconds keeps the bar smooth, and the result is always right even if a tick runs late.

Second, a timer must always be stopped. If you forget, an old interval keeps running into the next question, or even the next game, and calls timeUp() at random moments. So there's exactly one timerId, startTimer() always stops the previous timer first, and every way of leaving a question (answering, timing out) calls stopTimer().

The timer isn't part of state, and the tick doesn't call the full render(). Rebuilding the option buttons five times a second would be wasteful and would break hover and focus. A small renderTimer() updates only the bar and the text.

When time runs out, the game records the answer as -1, meaning "nothing picked", which never matches a real option. Correct answers now earn a speed bonus: up to 50 extra points, in proportion to the time left.

Step 4: 15 seconds per question

Try letting a question run out, and try answering quickly versus slowly to see the bonus change. Notice how timeUp() doesn't need its own logic: it reuses choose(), so a timeout is scored, recorded and rendered exactly like a wrong answer. One path through the code means one place to fix bugs.

Why read the clock before stopTimer()? It isn't strictly necessary here, because stopTimer() doesn't touch deadline. But it makes the intent obvious: the bonus is based on the moment the user clicked. If you later change stopTimer() to reset the deadline, the bonus still works.

Step 5: Results, shuffling and a best score

The game works, but the results screen is thin and every round asks the questions in the same order. This step adds:

  • A review list. The answers array already holds everything needed: each question, what was picked, whether it was right and the points earned. renderResult() maps it to <li> elements.
  • A verdict. The percentage of correct answers picks one of three messages.
  • Shuffling. newGame() stores a shuffled copy of the questions in state.questions, and every function now reads questions from the state instead of from QUESTIONS. The shuffle is the Fisher–Yates algorithm: walk backward through the array and swap each item with a random one at or before it. It gives every order an equal chance, unlike the popular but biased sort(() => Math.random() - 0.5).
  • A best score for the session, shown on the start and results screens.
Step 5: Review answers and play again

Because the review list is built purely from state.answers, it can never disagree with the score. The destructuring at the top of renderReviewItem() pulls the four fields out of each record in one line.

The best score lives in an ordinary variable, so it's lost when the page reloads. On a real site you'd save it with localStorage. The editors here run in a sandbox where storage is blocked, so this is shown as read-only code:

JavaScript
// Load once at startup (stored values are strings, or null if missing)
let bestScore = Number(localStorage.getItem("quiz-best") ?? 0);

// Save when a game ends
function finishQuiz() {
  state.screen = "result";
  bestScore = Math.max(bestScore, state.score);
  localStorage.setItem("quiz-best", String(bestScore));
  render();
}

Step 6: Keyboard play and accessibility

The last stage makes the game comfortable without a mouse and clear for screen reader users:

  • Number keys. A keydown listener on the document maps 1–4 to the options while a question is open. Thanks to the guard clause in choose(), extra key presses after answering do nothing. The listener ignores presses with Ctrl, Alt or Meta held, so browser shortcuts keep working.
  • Focus management. Each new screen moves focus to its heading (made focusable with tabindex="-1"), so screen readers announce the question. After an answer, focus moves to the Next button, so Enter continues. There's no separate Enter handler; pressing Enter on a focused button clicks it natively.
  • Live feedback. The feedback paragraph has aria-live="polite", so "Correct!" or the explanation is read out when it appears. The ticking seconds are not live, because announcing a number five times a second would drown everything else out.
  • Reduced motion. The timer bar's animation turns off for people who ask for less motion in their system settings.

Click inside the preview first so it receives key presses, then play with the keyboard alone:

Step 6: The finished quiz game

That's the complete game. Look back at how little each piece knows about the others. The timer only calls timeUp(). Clicks and key presses only call choose(). choose() only changes the state. And render() only reads the state. You could add a new way to answer, say voice input, by writing one more line that calls choose().

Focus and hidden. An element inside a hidden section can't receive focus. That's why render() un-hides the right section before calling the screen's render function, which then moves focus. If you swap those steps, focus() silently does nothing.

More ideas to try

  • Load questions from JSON. Move QUESTIONS into a JSON file and load it with fetch(); show a "Loading…" screen while it arrives. In the sandbox, you can practice with new Response(JSON.stringify(QUESTIONS)).json().
  • Shuffle the options too. Shuffle each question's options and update answer to the new position of the right one, for example by shuffling indexes rather than strings.
  • Categories and difficulty. Add a category field, let players choose one on the start screen and filter() the questions.
  • Lifelines. A one-time "50:50" button that disables two wrong options.
  • Pause. Store the remaining milliseconds when paused, and set a new deadline from them when resumed.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Why does the timer compute the time left from a saved deadline instead of counting interval ticks?

    Browsers may delay timer callbacks. Reading the clock on each tick keeps the countdown accurate no matter when the tick runs.
  2. 2. What does the first line of choose() protect against?

    The guard returns early when the game isn't on a question or an answer was already picked, so clicks, keys and the timer can't score a question twice.
  3. 3. Why does startTimer() call stopTimer() before creating a new interval?

    Forgotten intervals keep running in the background. Clearing the old one first guarantees there is only ever one active timer.
  4. 4. The option buttons store their position in data-index. Why must the click handler use Number(button.dataset.index)?

    Everything in dataset is a string. Converting it lets the strict comparison with the numeric answer index work.
  5. 5. Which shuffle gives every order of the questions an equal chance?

    Fisher–Yates is unbiased and fast. Sorting with a random comparator is a popular trick, but some orders come up more often than others.

Summary

  • Keep the whole game in one state object (screen, questions, index, score, picked, answers) and let render() show exactly one screen from it.
  • Start each round from a fresh state object, so nothing leaks from the previous game.
  • Use event delegation for options that are re-created for every question, and convert dataset strings with Number().
  • Build countdowns from a deadline and the clock, keep one timer id, and stop it on every path out of a question.
  • Route every way of answering (click, key, timeout) through one function with a guard clause.
  • Shuffle with Fisher–Yates, build the results review from recorded answers, and support the keyboard with focus management and aria-live feedback.

Next: Project: Weather Dashboard — async data with loading and error states, formatted with Intl.