Javascript / jQuery or something to change text every some seconds

强颜欢笑 提交于 2019-11-28 18:24:46
Thomas Shields

As others have said, setInterval is your friend:

var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 1000);

function change() {
  elem.innerHTML = text[counter];
  counter++;
  if (counter >= text.length) {
    counter = 0;
    // clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle
  }
}
<div id="changeText"></div>

You may take a look at the setInterval method. For example:

window.setInterval(function() {
    // this will execute on every 5 seconds
}, 5000);
setInterval(function(){
   alert('hello, do u have a beer ?');
}, 1000);

where 1000ms = 1sec;

You can use setInterval to call a function repeatedly. In the function you can change the required text.

The list of texts to change between could be stored in an array, and each time the function is called you can update a variable to contain the current index being used. The value can loop round to 0 when it reaches the end of the array.

See this fiddle for an example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!