let score = 0;
let correctAnswer;
// Function to generate a new question and options
function generateQuestion() {
const num1 = Math.floor(Math.random() * 10) + 1; // Random number between 1 and 10
const num2 = Math.floor(Math.random() * 10) + 1; // Random number between 1 and 10
correctAnswer = num1 * num2; // Correct answer for the multiplication
// Display the question
document.getElementById('question').textContent = `What is ${num1} × ${num2}?`;
// Shuffle options
const options = [correctAnswer, Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100)];
options.sort(() => Math.random() - 0.5); // Shuffle options randomly
// Set the options on the buttons
const buttons = document.querySelectorAll('.button');
buttons.forEach((button, index) => {
button.textContent = options[index];
button.onclick = () => checkAnswer(options[index]);
});
// Clear the message
document.getElementById('message').textContent = '';
}
// Function to check the answer
function checkAnswer(userAnswer) {
if (userAnswer === correctAnswer) {
score++;
document.getElementById('message').textContent = 'Correct! 🎉';
document.getElementById('message').style.color = 'green';
} else {
document.getElementById('message').textContent = 'Try again!';
document.getElementById('message').style.color = 'red';
}
document.getElementById('score').textContent = `Score: ${score}`;
// Generate a new question after a short delay
setTimeout(generateQuestion, 1000); // 1-second delay before showing the next question
}
// Initialize the game by generating the first question
generateQuestion();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.