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

85
Vistas
Loop with setInterval

Sup, hope you all doing well!

I'm tryng to change each piece of a string to a random digit in a realtime loop but something is going bad here

I've shorted the code to find the problem but no sucess atm:

let count = 0;
let timer = setInterval(() => {
let rng = Math.floor(Math.random()*9);
let txtOriginal = document.getElementsByTagName('p')[0].innerHTML;

if (count < 8) {

let txtNew = document.getElementsByTagName('p')[0].innerHTML = txtOriginal.replace(txtOriginal.charAt(count), rng);
count++;

} else {
count = 0;
}
},500) 
<p>ABCDEFGH</p>

The first run goes as intended, but going foward it starts to change the values in a random order...

Should I try another metod?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You're doing

.replace(txtOriginal.charAt(count), rng)

When a string is passed to .replace, the first instance of the string found is replaced. For example, 'aa'.replace('a, 'b') results in 'ba'.

The first go around, no duplicate characters will be found; textOriginal.charAt(count) will always return a substring not present anywhere else. But starting at the second go around, now that the text is composed of numbers, txtOriginal.charAt(count) may well produce a numeric character that's also present earlier in the string. For example, if the string generated after the first time is 12345678, and the next iteration produces 22345678, the resulting

.replace('2', rng)

will replace the character at the index 0 again, instead of the character at index 1.

Slice the string instead, to replace with the desired character.

const p = document.querySelector('p');
let count = 0;
setInterval(() => {
  const newChar = Math.floor(Math.random() * 9);
  const text = p.textContent;
  if (count < 8) {
    p.textContent =
      text.slice(0, Math.max(0, count))
      + newChar
      + text.slice(count + 1);
    count++;
  } else {
    count = 0;
  }
}, 500)
<p>ABCDEFGH</p>

Or, perhaps use an array - adjusting it is a bit more intuitive than adjusting a string.

const p = document.querySelector('p');
let count = 0;
setInterval(() => {
  const newChar = Math.floor(Math.random() * 9);
  if (count < 8) {
    const textArr = [...p.textContent];
    textArr[count] = newChar;
    p.textContent = textArr.join('');
    count++;
  } else {
    count = 0;
  }
}, 500)
<p>ABCDEFGH</p>

about 4 years ago · Juan Pablo Isaza Denunciar
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