Skip to content
Advertisement

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement