Guide 3.8: Real Projects

Add a Countdown Timer

A CBT exam without a timer isn't a test; it's just a quiz. We need to implement a strict countdown timer that automatically forces submission when the time runs out.

Timer Logic

3.8.1

Open app.js and add a variable to hold the exam duration (in seconds), and a variable to hold the setInterval reference so we can clear it later.

let timeLeft = 45 * 60; // 45 minutes in seconds
let timerInterval;

function startTimer() {
  const display = document.getElementById('timerDisplay');
  
  timerInterval = setInterval(() => {
    if (timeLeft <= 0) {
      clearInterval(timerInterval);
      submitExam(); // Auto-submit when time is up!
      return;
    }
    
    timeLeft--;
    
    // Format mm:ss
    const minutes = Math.floor(timeLeft / 60);
    const seconds = timeLeft % 60;
    
    display.textContent = 
      `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      
    // Add visual warning when time is low (< 5 minutes)
    if (timeLeft < 300) {
      display.style.color = 'red';
      display.style.fontWeight = 'bold';
    }
  }, 1000);
}

Start the Timer

3.8.2

You must remember to call startTimer() exactly when the user sees the first question. Add it to your existing startExam() function.

function startExam() {
  document.getElementById('homeScreen').classList.remove('active');
  document.getElementById('examScreen').classList.add('active');
  
  generateNumberGrid();
  renderQuestion(0);
  
  // Start the ticking clock!
  startTimer();
}

How do we track selections?

Next, we will write the logic that securely records the user's answers in memory.

Next Guide: Answer System →
Avatar

How can we help?

We reply immediately

Hello! 👋 How can we help you today?