My goal is to execute a function that can print number 1-4; But in 1s intervals (and I don’t want to use setInterval). I’ve been trying and what I could do was to print all the elements in an array after one second delay. here’s the code :
const wait = async (number) => {
return new Promise(async(resolve)=>{
setTimeout(async()=>{
resolve();
},number);
})
}
const listElement = document.getElementById("list");
[1,2,3,4].map((num)=>{
const newListItemElement = document.createElement("li");
newListItemElement.innerHTML = num;
wait(1000).then(()=>{
console.log(num);
listElement.appendChild(newListItemElement);
})
})
<html>
<body>
<h3>list</h3>
<ul id="list">
</ul>
</body>
</html>
What I want this to do is to wait a second and print 1 then wait a second and print 2 and so on. The code I added in the snippet is making all the numbers appear together at once and this is because map function goes on even if the current iteration isn’t done yet.