Quiero un elemento HTML para cambiar su texto a una cadena que se almacena en una matriz y pasar por cada índice de la matriz. Estoy usando un bucle for y jQuery para establecer un elemento H1 en diferentes cadenas. Sé que está actualizando el valor del elemento cada vez que se ejecuta el ciclo, pero no muestra el cambio hasta que finaliza el ciclo. El objetivo es mostrar el ciclo del elemento a través de los nombres y luego aterrizar en uno para hacer una especie de animación Aquí está mi código:
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>