In our last section, we were able to make a single question appear. However, what if we want questions to appear a set number of times every time we answer a question?
Introducing the for loop. These are handy tools allowing us to perform actions repeatedly without having the write the code or call a function multiple times. What is the syntax of a for loop?
<script>
for(var i = 0; i < 5; i++)
{
}
</script>
As you can see, there a few parts here.
The result is that this loop runs five times, from 0 to 4. We can prove to ourselves by creating and running this page.
<html>
<title>for loops</title>
<head>
<script>
function theForLoop()
{
var result = "";
for(var i = 0; i < 5; i++)
{
result += i + "<br>";
}
document.getElementById("theResult").innerHTML = result;
}
</script>
</head>
<body onload="theForLoop();">
<div id="theResult"></div>
</body>
</html>
If you run this page, you see that all numbers print out from 0 to 4 right? So, how do we apply this to our game?
<html>
<title>for Loops</title>
<head>
<script>
var actualAnswer;
var number1;
var number2;
function printQuestion()
{
actualAnswer = number1 + number2;
document.getElementById("theQuestion").innerHTML = "What is " + number1 + "+" + number2 + "?";
}
function checkAnswer()
{
var answer = document.getElementById("txtAnswer").value;
if(answer == actualAnswer)
{
document.getElementById("finalResult").innerHTML = "Good job!";
runGame();
}
else
{
document.getElementById("finalResult").innerHTML = "Try Again!";
}
}
function runGame()
{
for(var i = 0; i < 5; i++)
{
number1 = Math.floor(Math.random() * 10);
number2 = Math.floor(Math.random() * 10);
}
printQuestion();
}
</script>
</head>
<body onload="runGame();">
<div id="theQuestion"></div>
<table>
<tr>
<td>Your answer</td>
<td><input type="text" id="txtAnswer"></td>
</tr>
<tr>
<td colspan="2"><button id="btnSubmit" onClick="checkAnswer();">Submit</button></td>
</tr>
</table>
<div id="finalResult"></div>
</body>
</html>
If you look carefully, you see that I create a third function called runGame and then call that function in the onload event of the body. Inside the body of the runGame function, I call the printQuestion function. Notice that the function call always ends with the () afterward to indicate that it is a function, and then I completed the line with a semi-colon ;.
Run this page. Does it work? Great!