0

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 ...

image one image two

0xff
  • 181
  • 2
  • 11
  • Yes there is. try it out yourself. I copy pasted my code from my IDE – 0xff Oct 17 '21 at 16:36
  • 3
    It's because the timeout doesn't pause the loop. All characters will be scheduled immediately and printed after their random timeout. So the ones with the shorted random timeout will be printed first. (Surely there is a dupe for this...) – Ivar Oct 17 '21 at 16:39
  • Can you suggest a way to fix this? – 0xff Oct 17 '21 at 16:39
  • You probably need to re-think the way the timeout works. There should be a timeout for each character that then schedules the timeout for the *next* character. – Pointy Oct 17 '21 at 16:41
  • Would recursion work for that? – 0xff Oct 17 '21 at 16:41
  • It's kind-of general good practice to delete comments that are off-target, because they're, well, wrong. Anyway, a `setTimeout()` that sets up another timeout looks kind-of like recursion, but it isn't really. You can think of it that way: the timeout increments the character index and (when necessary) the line index, which I think will give you the effect you want. – Pointy Oct 17 '21 at 16:46
  • Thanks! Will do that. – 0xff Oct 17 '21 at 16:46
  • Also relevant: [How do I add a delay in a JavaScript loop?](https://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) – Ivar Oct 17 '21 at 16:51

0 Answers0