javascript - 如何使用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。
〜问候
解决方案
您可以使用此辅助函数以所需的持续时间“暂停”代码的执行:
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
然后await timeout(3000)
。
请注意,外部函数必须是async
才能在await
其中使用
推荐阅读
- python - Python - 匹配单词但不匹配单词旁边的另一个单词
- c# - 如何在需要时创建棱镜的视图模型?
- excel - 使用 IF 和 AND 函数
- android - 推到新屏幕后底部导航栏未隐藏
- python - csv.read 不尊重字符串中的引号
- gensim - gensim doc2vec 嵌入向量中的差异
- java - 生成并读取 base64 私钥以从 java 签署 JWT 令牌
- python - 将宽表格式更改为长表格式并按年份拆分日期
- c# - SELECT COUNT(*) 认为字符串参数是一个 IEnumerable - 返回一个数组?(CockroachDB C#)
- flutter - 如何在 Flutter 中使用 Mobx 弹出屏幕