Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda