I want an HTML element to change it's text to a string that is stored in an array and go through each index in the array. I am using a for loop and jQuery to set an H1 element to different strings. I know it's updating the element's value each time the loop runs but it doesn't display the change until the loop is over. The goal is to show the element cycling through names and then land on one to make a kind of animation Here is my code:
var random = ["nameOne", "nameTwo", "nameThree", "nameFour"];
function pickName() {
var loopCycles = 20;//How many times should the animation cycle through the possible names
for (var i = 0; i <= loopCycles; i++) { //Atempt at trying to make a small animation where the HTML element cycles through the array
var name = random[Math.floor(Math.random() * 4)]; //Pick a name from the array: random
setTimeout($(".rng").html(name), 50);//Change the HTML element
console.log(name);//testing purposes
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet">
<title>RNG Name Picker</title>
</head>
<body>
<button class="button-53" role="button" onclick="pickName()">Pick name</button>
<h1 class="rng"></h1> <!--This is where the name will go-->
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="home.js"></script>
</html>