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.
JavaScript
x
13
13
1
function randNum(prevNum) {
2
let randNum = Math.round(Math.random() * 12) //choose a number between 0 and 12
3
while (randNum == prevNum){ //if the chosen number is the same as prevNum, choose another random number
4
randColor = Math.round(Math.random() * 12)
5
}
6
prevNum = randColor //assign current value to parameter
7
return (prevNum); //return parameter
8
}
9
10
11
prevNum = 0,
12
prevNum = setInterval (randNum, 1000, prevNum) //assign returned parameter to current variable, then go back into the function with the new parameter value.
13
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
.
JavaScript
1
15
15
1
let prevNum = 0;
2
3
function randNum() {
4
let newNum
5
while (true) {
6
newNum = Math.round(Math.random() * 12) //choose a number between 0 and 12
7
if (newNum != prevNum) {
8
break;
9
}
10
}
11
prevNum = newNum //save the current value
12
console.log(prevNum);
13
}
14
15
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.