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

294
Visualizações
How do I prevent a duplicate random number when using setInterval? (javascript)

I've been wanting to generate random numbers through a function and then use setInterval to repeat that function and give me a new number every time.

function randNum(prevNum) { 
    let randNum = Math.round(Math.random() * 12)     //choose a number between 0 and 12 
    while (randNum == prevNum){                //if the chosen number is the same as prevNum, choose another random number
        randColor = Math.round(Math.random() * 12) 
    }
    prevNum = randColor            //assign current value to parameter 
    return (prevNum);              //return parameter
}


prevNum = 0,
prevNum = setInterval (randNum, 1000, prevNum)     //assign returned parameter to current variable, then go back into the function with the new parameter value.

also using node so semicolons might be missing.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

When you use prevNum as a setInterval() argument, you're always passing the original value of the variable to the callback function. You should just use the global variable directly rather than passing it as a parameter.

You also have a typo, randColor should be randNum.

let prevNum = 0;

function randNum() {
  let newNum
  while (true) {
    newNum = Math.round(Math.random() * 12) //choose a number between 0 and 12 
    if (newNum != prevNum) {
      break;
    }
  }
  prevNum = newNum //save the current value
  console.log(prevNum);
}

let interval = setInterval(randNum, 1000)

The return value of the callback function isn't used, so there's no point in return prevNum;. And you shouldn't assign the result of setInterval() to your number variable -- it returns a timer ID, not the value of the function.

about 4 years ago · Juan Pablo Isaza Relatório

0

You could create a function that returns an iterator and keeps the state:

function randiter(n) {
    let num = 0;

    const iter = () => {
        let cur;
        do {
            cur = Math.round(Math.random() * n);
        } while (cur === num);
        num = cur;
        return num;
    };
    return iter;
}

The above version takes the max number as a parameter. Use it like so:

const p12 = randiter(12);

for (let i=0; i<20; i++) {
    console.log(p12());
}

or

setInterval(() => console.log(p12()), 1000);
about 4 years ago · Juan Pablo Isaza Relatório

0

I am the 3%
(and I miss Pascal)

let intervalRef = setInterval( ( prev ) =>
  {
  let newNum;
  do     newNum = Math.round(Math.random() * 12) 
  while( newNum === prev.val )

  prev.val = newNum

  console.log( newNum )
  }
  , 1000, { val: null } )
  
  
setTimeout(()=>clearInterval(intervalRef), 20000)

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