Cohchi
Cohchi

Reputation: 563

How to change text every 5 seconds

I have a line of text, with a span. I wanted to the text in span change every 5seconds. I made a script :

var texts = new Array();
texts.push("Text1");
texts.push("Text2");
texts.push("Text3");

var point = 0;

function changeText(){
  $('#cookie-alert .col h3 span').html(texts[point]);
  if(point < texts.length){
    point ++;
  }else{
    point = 0;
  }
  setInterval("changeText", 5000)
}

changeText();

So the array contains all the texts. So with this, the first text appears but not others. I have an error:

"ReferenceError: changeText is not defined" at line "setInterval("changeText", 5000)"

I don't understand where is my mistake

Upvotes: 1

Views: 10097

Answers (2)

mdatsev
mdatsev

Reputation: 3879

setInterval takes as its first argument the function, not the function's name as string like this:

setInterval(changeText, 5000)

But you really should be using setTimeout in the function like this:

var texts = new Array();
texts.push("Text1");
texts.push("Text2");
texts.push("Text3");

var point = 0;

function changeText(){
  $('h3').html(texts[point]);
  if(point < texts.length - 1){
    point ++;
  }else{
    point = 0;
  }
  setTimeout(changeText, 5000)
}

changeText();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3> </h3>

or simply setInterval like this:

var texts = new Array();
texts.push("Text1");
texts.push("Text2");
texts.push("Text3");

var point = 0;

function changeText(){
  $('h3').html(texts[point]);
  if(point < texts.length - 1){
    point ++;
  }else{
    point = 0;
  }
}
changeText();
setInterval(changeText, 5000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3> </h3>

Edit: To work flawlessly you wanna have the if be if(point < texts.length - 1) so it repeats at the same rate.

Upvotes: 2

Eddie
Eddie

Reputation: 26854

  1. You have to pass the changeText as a function and not a text.
  2. You have to call setInterval outside the fuction changeText
  3. As suggested, need to use texts.length - 1 coz you start counting from 0.

var texts = new Array();
texts.push("Text1");
texts.push("Text2");
texts.push("Text3");

var point = 0;

function changeText(){
  $('#cookie-alert .col h3 span').html(texts[point]);
  if(point < ( texts.length - 1 ) ){
    point++;
  }else{
    point = 0;
  }
  
}
 
setInterval(changeText, 5000); /*Call it here*/
changeText();

Upvotes: 2

Related Questions