Reputation: 35
I have managed to loop through the alphabet array but in random order when i click the roll button. How can i loop through the array but in the correct order and when it reaches at Z to start at the beginning again without stopping.
function roll() {
var alphabet = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
];
setInterval(function () {
for (i = 0; i < alphabet.length; i++) {
document.querySelector("span").innerHTML =
alphabet[Math.floor(Math.random() * alphabet.length)];
}
}, 800);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Document</title>
</head>
<body>
<div class="main">
<span></span>
<button id="roll" onclick="roll()">roll</button>
</div>
<script src="main.js"></script>
</body>
</html>
Upvotes: 0
Views: 72
Reputation: 221
function roll() {
var i=0;
var alphabet = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
];
setInterval(function () {
if (i == alphabet.length){
i=0;
}
document.querySelector("span").innerHTML = alphabet[i];
i++;
}, 800);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Document</title>
</head>
<body>
<div class="main">
<span></span>
<button id="roll" onclick="roll()">roll</button>
</div>
<script src="main.js"></script>
</body>
</html>
Upvotes: 1