Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda