开发者

JavaScript / jQuery or something to change text every some seconds

I need JavaScript or jQuery something to change text every few seconds... without the user doing anything.

Example:

"Welcome" changes to "Salmat datang" changes to "Namaste", etc. afte开发者_运维技巧r 3 seconds and loops back.


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);


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.


setInterval(function(){
   alert('hello, do you have a beer?');
}, 1000);

where 1000 ms = 1 second.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜