首页 > 解决方案 > 如何使用javascript逐个添加元素并在浏览器中更新?

问题描述

所以如下所示,我有一个在单击按钮时执行的函数,它向文档中添加了 30 个具有一些属性的 div 元素。

var bar_counter = 0;
bar_lengths = new Array();
function createBar(btnObj)
{
    while(bar_lengths.length < 30){
        var size =  Math.floor(Math.random() * (50 - 1) ) + 1;
        
        if(size>50)
        {
            alert("Please enter a value between 1 and 50 only!");
        }
        else{
            if(bar_lengths.indexOf(size) === -1){
                bar = document.createElement("div");
                bar_counter = parseInt(bar_counter) + parseInt(1);
                bar.setAttribute("class","bars");
                bar.setAttribute("name","bar"+bar_counter);
                bar.setAttribute("id",size);
                bar.style.height=10*size+"px";
                var color1 = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
                var color2 = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
                
                bar.style.backgroundImage="linear-gradient(359deg,"+color1+","+color2+")";
                bar.insertAdjacentHTML("beforeend","<font color='red' style='vertical-align: text-bottom; background-color:white'>"+size+"</font>");
                bar.insertAdjacentHTML("beforeend","<font color='red' style='vertical-align: text-bottom; background-color:white'> </font>");
                var place_to_insert = document.getElementById("placeBars");
                place_to_insert.appendChild(bar);
                bar_lengths.push(size);
            }
        }
    }
    btnObj.disabled=true;
    temp="";
    for(var i= 0; i < bar_lengths.length; i++) {
        temp = temp+bar_lengths[i]+" , ";
    }
    document.getElementById("YourArray").innerHTML = temp;
}

它运行良好,但在单击按钮时,浏览器窗口会立即填充 30 个 div 元素。我想要做的是在这个循环中添加一个延迟,以显示它们在窗口中被一一添加。我该怎么做?我尝试使用 setTimeout() 和 setInterval() 函数,但没有奏效。TIA。

〜问候

标签: javascripthtmlcss

解决方案


您可以使用此辅助函数以所需的持续时间“暂停”代码的执行:

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

然后await timeout(3000)

请注意,外部函数必须是async才能在await其中使用


推荐阅读