user97919
user97919

Reputation: 17

How to call a function every 1-3 second?

My goal is to write a mini-game using canvas, one of the task is to create "bug" object entering the scene between every 1-3 seconds. I did try functions like setTimeOut,setInterval but I couldn't get it right. Here is my attempt

  bugs =[];
  function addBug(){
     var bug = createBug();
     bugs.push(bug);
  }

  function createRandomNumber(max){
     return Math.floor((Math.random() * max) + 1);
  };

  var enterBug = setInterval(addBug,createRandomNumber(10)*1000);

currently I got it spawning at constant rate but don't know how to change it to every 1-3.Any suggestion? thanks in advance.

Upvotes: 0

Views: 211

Answers (1)

Mike Brant
Mike Brant

Reputation: 71422

Currently, you are only setting the rate once at initial setInterval call. You would likely need to use setTimeout like this:

...
function addBug(){
   ...
   bugTimeout = setTimeout(addBug, createRandomNumber(10)*1000);
}
...
bugTimeout = setTimeout(addBug, createRandomNumber(10)*1000);

You also may think about your random number generation if you want to get more randomness. Right now you can only get exact second values 1-10 since you are multiplying by 1000 to convert to seconds AFTER the random generation is done. If you want something more random you might use:

function createRandomNumber(maxSeconds){
    minSeconds = 1;
    if (maxSeconds < minSeconds) {
        maxSeconds = minSeconds;
    }
    interval = maxSeconds - minSeconds;
    return (Math.floor(Math.random() * interval) + minSeconds) * 1000;
};

You of course would not need to multiply by 1000 anymore when setting timeout.

bugTimeout = setTimeout(addBug, createRandomNumber(10))

Upvotes: 3

Related Questions