Jquery replace text every 2 seconds with words from an array

This is easily achievable using just Vanilla JS (normal JS without jQuery) as shown below.

Create a setInterval() loop to run every 2 seconds and randomize each time to get a different array element.

var names = ['test1', 'test2', 'test3', 'test4'];

setInterval(function() {
  var rand = Math.floor(Math.random() * 4);
  document.getElementById("name").innerHTML = names[rand];
}, 2000);
<div id="name">test</div>

If you want to have a fading effect (as mentioned in a comment) your best option will be to use jQuery.


You can use setInterval() to do this:

$(function () {
  count = 0;
  wordsArray = ["Beta", "Gamma", "Delta", "Alpha"];
  setInterval(function () {
    count++;
    $("#word").fadeOut(400, function () {
      $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
    });
  }, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="word">Alpha</div>