How to Use setTimeout in a for…loop

后端 未结 4 1113
北恋
北恋 2021-01-16 11:35

What I want is this (news ticker type functionality):

  1. Get a list of li\'s from a ul tag
  2. Loop through all the li\'s and get the text
  3. display t
4条回答
  •  一生所求
    2021-01-16 12:04

    Change this:

    for(var x=0; x < li.length; x++){
        var li_text = li[x].childNodes[0].nodeValue;
        setTimeout(function(){showText(li_text)}, 1000);
    }
    

    To:

    for(var x=0; x < li.length; x++) (function() {
        var li_text = li[x].childNodes[0].nodeValue;
        setTimeout(function(){showText(li_text)}, x * 1000);
    })()
    

提交回复
热议问题