Reputation: 65
I'm currently attempting to update the innerHTML of an h1 multiple times in one functions. The idea is that on load, the h1 would show a random name based on an array, every second, about five times, before console logging. Basically, wait, name, log, wait, name, log, etc. Currently, what is happening is wait, log, wait, log, wait, log, wait, log, name.
How can I make it so a new name is displayed in the h1 each time? Here's the code I'm currently working with:
let Names = ["John", "Mike", "Dan"];
//This is to pause it before moving on
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function rapidNames() {
let xyz = document.getElementById('name-changer');
for (let i = 0; i <5; i++) {
sleep(500);
xyz.innerHTML = Names[Math.floor(Math.random() * Names.length)];
console.log(1);
}
}
The result is
1
1
1
1
<Name Changes>
I've tried several different ways of putting them and organizing them in other oders and I just can't quite get it. Thanks in advance.
Upvotes: 0
Views: 122
Reputation: 48600
You should make these functions asynchronous (async
) and await
the sleep
promise to resolve
.
let Names = ["John", "Mike", "Dan"];
function randomName() {
return Names[Math.floor(Math.random() * Names.length)];
}
async function sleep(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
async function rapidNames() {
let xyz = document.getElementById('name-changer');
for (let i = 0; i < 5; i++) {
await sleep(500);
xyz.innerHTML = randomName();
console.log(i);
}
}
rapidNames();
<h1 id="name-changer"></h1>
Upvotes: 1