I've been working on a small side project, a website. I'm rather new to JS, so I googled a lot of stuff and relatively easily got some stuff done. One of the things I do is draw a String one character at a time with a little randomised timeout.
I also use a method to add a char to the output. My code looks the following:
let content = "";
let desiredContent = "public static void main (String[] args) {\n\tSystem.out.println(\"Hello, World!\");\n}";
let lines = desiredContent.split("\n");
schedule();
// for all lines and chars output them.
function schedule() {
for (let i = 0; i < lines.length; i++) {
for (let charIndex = 0; charIndex < lines[i].length; charIndex++) {
setTimeout(addChar, Math.random() * 50 + 50, lines[i].charAt(charIndex));
}
}
}
// add a char and update the output
function addChar(c) {
//console.log(c);
content += c;
codeBlockText.innerText = content;
}
The funny thing and what I don't understand is, that everytime I refresh the output seems to be completely randomised. All characters are there, in a seemingly random order. The only random element is the timeout, which I made sure actually is the timeout.
When I make the timeout constant it looks like it works out ...
My question is, if the randomized timeout messes with the internal thread stuff or if I messed up somewhere ...
Aucun commentaire:
Enregistrer un commentaire