0

n is the same every loop, even though i set it differently every iteration of setInterval. Anyone know a fix or another way I can randomise n every time?

    var n = random(1000, 5000);
let toptimer = setInterval(()=>{
    n = random(1000, 5000);
    obs.push(new obstacle(800, 200, 255));
},n);
  • Do you want to generate random numbers in a range of 1000 to 5000 is this? – Aks Jacoves Jun 12 '20 at 16:33
  • Until we know what `random` is doing, we can't tell you why it's returning the same val. – lux Jun 12 '20 at 16:33
  • 1
    why are you doing `var n = random(1000, 5000);` twice? – Red Baron Jun 12 '20 at 16:33
  • 3
    Try: n = Math.floor(Math.random() * 4001 + 1000) – Aks Jacoves Jun 12 '20 at 16:35
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Peter O. Jun 12 '20 at 16:38

2 Answers2

0

The thing you want to achieve cannot be implemented in setInterval as far as I think. You can use setTimeout as following and get the work done.

function foo() {
  var n = random(1000, 5000);
  setTimeout(()=>{
    obs.push(new obstacle(800, 200, 255));
    foo();
  },n);
}

And I hope you have a function "random" like this,

function random(min,max){ return min+((max-min)*Math.random());  }
Shaikh Amaan FM
  • 312
  • 4
  • 12
0

when you call setInterval(func,interval) you set the interval as a parameter and then func is called periodically.

if you want to change duration You should try this

var n = random(1000, 5000);
var exit = false;
var func = () => {
  if(!exit) {
    n = random(1000, 5000);
    obs.push(new obstacle(800, 200, 255));
    setTimeOut(func , n );
  }
}
setTimeOut(func,n);
Ehsan Nazeri
  • 771
  • 1
  • 6
  • 10