Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
Javascript setTimeout randomising output

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!