1

I have an array which contain some text descriptions. I want to display one element at a time with time delay (10 sec). After show all elements, it should be start again.

var d = 0;
var dataList = ["a","b","c"];//eg:
function ShowList()
{
    do{
       var descrip = dataList[d];
       document.getElementById('section1').innerHTML = descrip;
       d++;
       setTimeout(ShowList(),10000);

    }while(d < dataList.length);
}
ShowList();

I'll try with above code, but not working properly.

user2870117
  • 113
  • 9
  • 1
    If you only want to display one element at a time, there is no need for the loop. A loop is synchronous, setTimeout is asupynchronous. – Felix Kling Mar 10 '16 at 14:33
  • Also, make sure to do the wrap around at the beginning `if (d >= dataList.length) d = 0;` – 4castle Mar 10 '16 at 14:37

4 Answers4

3

As the other answers correctly say, you need to pass the function itself to setTimeout, not call the function.

What they are not saying is that using a loop won't work here because setTimeout is asynchronous. Just set the element content and call setTimeout:

var d = 0;
var dataList = ["a","b","c"];//eg:
function showList() {
    var descrip = dataList[d];
    document.getElementById('section1').innerHTML = descrip;
    d = (d + 1) % dataList.length;
    setTimeout(showList, 10000);
}
showList();

To start from the beginning, we use the modulus operator, so that d is always in the range [0, d.length).

Stefano Nardo
  • 1,567
  • 2
  • 13
  • 23
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
3

You can use setInterval() instead.

setTimeout executes the function once on a time out. setInterval executes the function repeatedly on and interval

source

Code example

var d = 0,
  dataList = ['a', 'b', 'c'];

setInterval(function() {
  var descrip = dataList[d];
  document.getElementById('section1').innerHTML = descrip;
  d++;
  if (d >= dataList.length) {
    d = 0;
  }
}, 10000);

To stop the interval, use clearInterval()

Community
  • 1
  • 1
R3tep
  • 12,512
  • 10
  • 48
  • 75
1

Use setTimeout(ShowList,10000); instead of setTimeout(ShowList(),10000);

Dmitriy
  • 3,745
  • 16
  • 24
0

In setTimeout you have to specify the name of the function, not the application. When you write func() you are executing the function and the result will be passed as the actual parameter of setTimeout. For example, if func() returns 2, when you write setTimeout(funct(), 1000) it is like you are writing setTimeout(2, 1000).

Therefore write setTimeout(ShowList, 10000);

Stefano Nardo
  • 1,567
  • 2
  • 13
  • 23