4eyes 4eyes - 6 months ago 16
HTML Question

Show elements of array one by one - Jquery

So i have a button on which i want to display each element of my array for a few seconds. This is my html code.

<button class="btn" id="random">Start</button>


i have made an array with jQuery that i want to use to change the buttons text

$(document).ready(
function(){
$("#random").on("click", loop);
}
);

var array = ["el1","el2","el3"];

function loop(){
for (i = 0; i < array.length; i++){

$("#random").html(array[i]);

}
var random = Math.floor(Math.random() * array.length) + 1;
$("#random").html(array[random]);
}


the for loop is supposed to do what i want but i can't find a way to delay the speed, it always just shows the last line of code. when i try setTimeout or something it just looks like it skips the for loop.

Answer

Use setInterval() and clearInterval()

$(document).ready(
  function() {
    $("#random").on("click", loop);
  }
);

var array = ["el1", "el2", "el3"];
var int;

function loop() {
  var i = 0; // variable for array index
  int && clearInterval(int); // clear any previous interval
  int = setInterval(function() { //store interval reference for clearing
    if (i == array.length) clearInterval(int); // clear interval if reached the last index
    $("#random").text(i == array.length ? 'Start' : array[i++]); // update text with array element atlast set back to button text
  }, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="btn" id="random">Start</button>

Comments