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

84
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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