0

The following code does not work. That is, I am making an array with the values, but it does not work with the setTimeout.

I do not know what to do? Or I'm doing wrong the data interpretation.

The functionality is to change the text every 1 sec, but I can not make it work.

HTML:

<span class="title"></span>

JS:

var month = [
  "One Month",
  "Two Month",
  "Three Month",
  "Four Mounth"
];

var number = month.length;

function doSetTimeout(i) {
  setTimeout(function() {
    $(".title").text(month[i]);
  }, 1000);
}

for (var i = 0; i < number; i++) {
  doSetTimeout(i);
}

JSFIDDLE:

Link: https://jsfiddle.net/2uxdjp3j/2/

Hendrix
  • 179
  • 10
  • You set them all to run after 1 second. So, after 1 second, the text is changed to each value, one after the other, immediately. Either do it recursively, or increase the delay of each iteration. – Kevin B May 15 '17 at 19:24
  • The text should change every second or at least the general idea. – Hendrix May 15 '17 at 19:29
  • Right. but your code waits one second, then does all of the changes because you set the delay to 1 second for all of them. setTimeout does not make the for loop wait. – Kevin B May 15 '17 at 19:30
  • Possible duplicate of [setTimeout in for-loop does not print consecutive values](http://stackoverflow.com/questions/5226285/settimeout-in-for-loop-does-not-print-consecutive-values) – Heretic Monkey May 15 '17 at 19:30
  • this is a dupe, but not of a for loop closure... – Kevin B May 15 '17 at 19:31

1 Answers1

0

Your code is setting the timer to change the text with a delay of 1 second. However, each of the timers are set with the same delay, so it is happening more quickly than you can perceive the change. Try incrementing the timeout value like this:

function doSetTimeout(i) {
  setTimeout(function() {
    $(".title").text(month[i]);
  }, 1000+(i*1000));
}
Kevin B
  • 94,570
  • 16
  • 163
  • 180
aengus
  • 605
  • 6
  • 13