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?
Here we introduce the for loop. This tool allows us to repeat an action without duplicating code or calling a function multiple times one after another. 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() {
number1 = Math.floor(Math.random() * 10);
number2 = Math.floor(Math.random() * 10);
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!";
printQuestion();
} else {
document.getElementById("finalResult").innerHTML = "Try Again!";
}
}
function runGame() {
for (var i = 1; i < 6; i++) {
document.getElementById("message").innerHTML += "<h" + i + ">Welcome to our game!!!</h" + i + "></p>";
}
printQuestion();
}
runGame();
</script>
</head>
<body onload="runGame();">
<table>
<tr>
<td colspan="2">
<div id="message"></div>
</td>
</tr>
<tr>
<td colspan="2">
<hr size="1">
</td>
</tr>
<tr>
<td colspan="2">
<div id="theQuestion"></div>
</td>
</tr>
<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 display a message about our game and then 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!
See the Pen JS - for loops by Michael Cassens (@retrog4m3r) on CodePen.