I want to simulate an autocomplete function. A sentence should be completed with words from a list. These words should be displayed char by char at the end of the sentence.
This is the HTML:
<p>We can help you with<span id="complete"></span></p>
This is part of the JS:
let words = ["design", "frontend", "backend"];
let output = document.getElementById("complete");
First I tried this:
words.forEach((e) => {
for (i = 0; i < e.length; i++) {
setTimeout(() => {
console.log(e[i]);
}, 500);
}
});
console logged:
I think it is because the iterator steps forward before the setTimeout.
So I tried a while loop like this:
words.forEach((e) => {
let i = 0;
while (i <= e.length) {
setTimeout(() => {
console.log(e[i]);
}, 600);
i++;
}
});
I got this:
I have no idea how to place character by character – so that they add up to the word like: d; de; des; desi; desig; design with kind of a delay between each character.
(To place the words char by char in the DOM, I would not use console log, but complete.innerHTML += variableForWordinList[index for char])
Thank you