Project: Quiz App
This project builds a quiz for new Fee Tracker office staff: questions about fee policies, loaded from a JSON file, answered one at a time against a countdown. It combines fetch, a small state machine (loading, answering, finished), timers that must be cleaned up, a fair shuffle, and a results screen. The quiz logic is written as pure functions so it can be tested, and the page code only renders state and dispatches events.
What You'll Build
- Questions loaded with
fetchfromquestions.json, with loading and error states. - One question at a time, answered by clicking (or keyboard) on real buttons.
- Immediate feedback, a score, and a 20-second timer per question (an unanswered question counts as wrong).
- Answer options shuffled with Fisher-Yates.
- A review screen listing each mistake with the correct answer.
Step 1: The Data
[
{ "id": 1, "question": "How many grace days before a late fee applies?", "options": ["5", "10", "15", "30"], "answer": "10" },
{ "id": 2, "question": "What is the maximum late fee?", "options": ["$20", "$25", "$30", "$50"], "answer": "$30" },
{ "id": 3, "question": "Which payment method has no processing fee?", "options": ["Card", "Check", "ACH", "PayPal"], "answer": "Check" }
]Storing the correct text (rather than an index) means shuffling the options can't break the answer key.
Step 2: The Quiz as a State Machine
A quiz is always in exactly one phase. Making the phases explicit prevents impossible situations, such as answering while results are showing:
| Phase | Shows | Allowed actions |
|---|---|---|
loading | "Loading questions..." | loaded, failed |
asking | The current question | answered, timedOut |
feedback | Right or wrong, and the correct answer | next |
finished | Score and review | restarted |
error | An error message | restarted |
function quizReducer(state, action) {
switch (`${state.phase}:${action.type}`) {
case "loading:loaded":
return { phase: "asking", questions: action.questions, index: 0, answers: [] };
case "loading:failed":
return { phase: "error", message: action.message };
case "asking:answered":
case "asking:timedOut": {
const q = state.questions[state.index];
const choice = action.type === "answered" ? action.choice : null;
return { ...state, phase: "feedback", answers: [...state.answers, { id: q.id, choice, correct: choice === q.answer }] };
}
case "feedback:next":
return state.index + 1 < state.questions.length
? { ...state, phase: "asking", index: state.index + 1 }
: { ...state, phase: "finished" };
default:
return state;
}
}
const questions = [{ id: 1, answer: "10" }, { id: 2, answer: "$30" }];
let s = { phase: "loading" };
for (const a of [{ type: "loaded", questions }, { type: "answered", choice: "10" }, { type: "answered", choice: "x" }, { type: "next" }, { type: "timedOut" }, { type: "next" }]) {
s = quizReducer(s, a);
console.log(a.type.padEnd(8), "->", s.phase);
}
console.log(s.answers.map((x) => x.correct));loaded -> asking
answered -> feedback
answered -> feedback
next -> asking
timedOut -> feedback
next -> finished
[true, false]The second "answered" was ignored (the quiz was already showing feedback), so only two answers were recorded: the first correct, and the timed-out one wrong.
const score = (answers) => answers.filter((a) => a.correct).length;
const grade = (n, total) => `${n} of ${total} (${Math.round((n / total) * 100)}%)`;
console.log(grade(score([{ correct: true }, { correct: false }, { correct: true }]), 3));2 of 3 (67%)Step 3: A Fair Shuffle
The tempting options.sort(() => Math.random() - 0.5) is biased: some orders come up far more often than others. The Fisher-Yates shuffle is correct and fast:
function shuffle(items, random = Math.random) {
const a = [...items];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
const counts = new Map();
for (let n = 0; n < 60_000; n++) {
const key = shuffle(["A", "B", "C"]).join("");
counts.set(key, (counts.get(key) ?? 0) + 1);
}
const shares = [...counts.values()].map((c) => c / 60_000);
console.log(counts.size, "orders, each about 1/6:", shares.every((s) => Math.abs(s - 1 / 6) < 0.01));6 orders, each about 1/6: trueAll six possible orders appear about equally often. Taking random as a parameter lets tests pass a fixed sequence for predictable results.
Step 4: The Timer
Each question gets 20 seconds. The timer must be cleared whenever the phase changes, or a timer from an earlier question could fire later and mark the wrong question:
let timer;
function startTimer(seconds, onTick, onDone) {
clearInterval(timer);
let left = seconds;
onTick(left);
timer = setInterval(() => {
left -= 1;
onTick(left);
if (left <= 0) {
clearInterval(timer);
onDone();
}
}, 1000);
}
const stopTimer = () => clearInterval(timer);The reducer's phase check is a second safety net: a timedOut arriving after the question was answered is ignored.
The Complete App
For the check, each question gets 1 second instead of 20. The checker answers question 1 correctly, question 2 wrongly, and lets question 3 time out:
<main id="quiz"><p id="status">Loading questions...</p></main>
<script type="module">
const SECONDS = 1;
const root = document.querySelector("#quiz");
let state = { phase: "loading" };
let timer;
function reducer(s, a) {
switch (`${s.phase}:${a.type}`) {
case "loading:loaded": return { phase: "asking", questions: a.questions, index: 0, answers: [] };
case "loading:failed": return { phase: "error", message: a.message };
case "asking:answered":
case "asking:timedOut": {
const q = s.questions[s.index];
const choice = a.type === "answered" ? a.choice : null;
return { ...s, phase: "feedback", answers: [...s.answers, { q, choice, correct: choice === q.answer }] };
}
case "feedback:next":
return s.index + 1 < s.questions.length ? { ...s, phase: "asking", index: s.index + 1 } : { ...s, phase: "finished" };
default: return s;
}
}
const el = (tag, props = {}, ...children) => { const e = Object.assign(document.createElement(tag), props); e.append(...children); return e; };
function render(s) {
clearInterval(timer);
if (s.phase === "asking") {
const q = s.questions[s.index];
const left = el("p", { id: "timer", textContent: `${SECONDS}s left` });
root.replaceChildren(
el("h2", { textContent: `Question ${s.index + 1} of ${s.questions.length}` }),
el("p", { textContent: q.question }),
...q.options.map((o) => { const b = el("button", { type: "button", textContent: o }); b.dataset.choice = o; return b; }),
left,
);
let seconds = SECONDS;
timer = setInterval(() => { seconds -= 1; left.textContent = `${seconds}s left`; if (seconds <= 0) dispatch({ type: "timedOut" }); }, 1000);
} else if (s.phase === "feedback") {
const last = s.answers.at(-1);
const text = last.correct ? "Correct!" : last.choice === null ? `Time's up. The answer is ${last.q.answer}.` : `Not quite. The answer is ${last.q.answer}.`;
root.replaceChildren(el("p", { role: "status", textContent: text }), el("button", { type: "button", id: "next", textContent: "Next" }));
console.log(`Q${s.index + 1}: ${text}`);
} else if (s.phase === "finished") {
const right = s.answers.filter((a) => a.correct).length;
const review = s.answers.filter((a) => !a.correct).map((a) => el("li", { textContent: `${a.q.question} Correct answer: ${a.q.answer}` }));
root.replaceChildren(el("h2", { textContent: `Score: ${right} of ${s.answers.length}` }), el("ul", {}, ...review));
console.log(root.querySelector("h2").textContent, "| to review:", review.length);
} else if (s.phase === "error") {
root.replaceChildren(el("p", { textContent: s.message }));
}
}
function dispatch(action) {
const next = reducer(state, action);
if (next !== state) { state = next; render(state); }
}
root.addEventListener("click", (e) => {
const choice = e.target.closest("[data-choice]")?.dataset.choice;
if (choice) dispatch({ type: "answered", choice });
if (e.target.id === "next") dispatch({ type: "next" });
});
try {
const res = await fetch("/questions.json");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
dispatch({ type: "loaded", questions: await res.json() });
} catch (err) {
dispatch({ type: "failed", message: `Couldn't load the quiz (${err.message}).` });
}
</script>Q1: Correct!
Q2: Not quite. The answer is $30.
Q3: Time's up. The answer is Check.
Score: 1 of 3 | to review: 2(For a predictable check, this version doesn't shuffle; add shuffle(q.options) when rendering in your own copy.)
Practice
Challenge: Add a "best score" feature: after finishing, compare the score with the best one saved, and report whether it's a new record. The logic, testable on its own:
Show solution
function updateBest(previousBest, score, total) {
const percent = Math.round((score / total) * 100);
const isRecord = previousBest === null || percent > previousBest;
return { best: isRecord ? percent : previousBest, isRecord };
}
console.log(updateBest(null, 2, 3), updateBest(67, 2, 3), updateBest(67, 3, 3));{ best: 67, isRecord: true } { best: 67, isRecord: false } { best: 100, isRecord: true }In the page, read the previous best from localStorage when the quiz finishes, call updateBest, save the result, and show "New record!" when isRecord is true.
Key Takeaways
| Piece | Technique |
|---|---|
| Phases | switch on phase:action |
| Data | fetch + res.ok + json() |
| Shuffle | Fisher-Yates |
| Timer | setInterval, cleared on render |
| Results | Derived score, review list |
Was this tutorial helpful?