简体   繁体   中英

javascript settimeout inside loop and repeat

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM