i am trying to make a simple list where each item is going to show after another
html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src = "async.js"></script>
</body>
</html>
javaScript
let list = [
{
name: 'one',
},
{
name: 'two',
}
]
let output = '';
function print(){
setTimeout(()=>{
list.forEach(function(element){
output = `<li>${element.name}</li>`; // critical line
document.body.innerHTML += output;
})
},500)
}
function add(element){
setTimeout(() =>{
list.push(element);
},400)
}
add({name: 'three'});
let c=0;
setTimeout(()=>{ // waits for add function to be executed
for(let i=0;i<list.length;i++){
setTimeout(print,c);
c+=1000;
}
},1000)
The problem is that output value gets all of names every iteration and prints 3 names 3 times instead of printing 1 name at the time. Can you explain this?