I have a function called chat chattext, which purposes is to write text to a box letter by letter.
function chattext(chat) {
playaudio("talking.mp3");
document.getElementById("chat").style.display = "block";
document.getElementById("chat").innerHTML = "";
var count = 0;
function update() {
console.log(count);
document.getElementById("chat").innerHTML += `${chat.substring(
count - 1,
count
)}`;
if (++count < chat.length) {
setTimeout(update, 50);
} else {
}
}
update();
}
And in another file I execute it like chattext("hello world")
which works fine, but if I execute it something after that like
like
chattext("hello world")
chattext("hi")
it will do both at the same time and output "hhello worl"
not wanted result
so im wondering how can I make it so the 2nd execution of the function will wait for the first to finish?
2
Answers
As it is, you have no way of knowing when a single invocation of
chattext
has finished, and if you call it twice in succession (while one is still busy), both invocations will "fight" over the text field.You’ll have a better time turning it into an
async
function, which will also mean you’ll need anasync
delay function, provided below.And naturally the function(s) you call that function from will need to be
async
so you canawait
forchattext
‘s completion.One option is to put the words to print into an array and constantly check the array.
You could optimize this by clearing the interval when the list is empty and restarting it when adding a word to an empty list.