How to Use setTimeout in a for…loop

后端 未结 4 1115
北恋
北恋 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:08

    How about we just move some of the code around a bit... take out the closure issue...

    var ul = document.getElementById('post_list');
    var li = ul.getElementsByTagName('li');
    
    for (var x = 0, xl = li.length; x < xl; x++) {
        var li_text = li[x].innerText || li[x].textContent; // does IE support textContent??
        showText(li_text, x * 1000);
    }
    
    function showText(text, delay) {
        setTimeout(function() {
            console.log(text);
        }, delay);
    }
    

    I assume the delay you want to be sequential (hence the loop). Because setTimeout is not blocking you will need to have a callback on the function to invoke the next setTimeout or you will need to specifically increment each function call with a new delay.

提交回复
热议问题