โ“ Projects

Build a Quiz App in JavaScript โ€” State, Timer, Score

๐Ÿ“… Jul 5, 2026 โฑ 4 min read

A quiz app teaches state management the honest way โ€” current question, score, timer, all coordinated by hand.

The state machine

const questions = [
  { q: "What does CSS stand for?", options: ["Cascading Style Sheets", "Computer Style System", "Creative Style Syntax"], answer: 0 },
  // ...load 100s from a JSON file or an API
];

let current = 0, score = 0, timeLeft = 15, timer;

function showQuestion() {
  const { q, options } = questions[current];
  qEl.textContent = `${current + 1}. ${q}`;
  optsEl.innerHTML = options.map((o, i) =>
    `<button data-i="${i}">${o}</button>`).join("");
  startTimer();
}

optsEl.addEventListener("click", (e) => {
  const btn = e.target.closest("button");
  if (!btn) return;
  clearInterval(timer);
  const correct = +btn.dataset.i === questions[current].answer;
  if (correct) score++;
  btn.classList.add(correct ? "right" : "wrong");
  setTimeout(next, 700);
});

function next() {
  current++;
  current < questions.length ? showQuestion() : showResults();
}

The timer

function startTimer() {
  timeLeft = 15;
  timer = setInterval(() => {
    timerEl.textContent = --timeLeft;
    if (timeLeft === 0) { clearInterval(timer); next(); }
  }, 1000);
}

Portfolio upgrades

โ† All Articles