Reputation: 340
I'm working on a game in JavaScript, and I want to change the way it behaves. What I am looking for is a way to change the direction of gravity every 10 seconds.
Here is my setInterval code, called in my draw() function, being ran whilst the game runs:
setInterval(function(){
changeGravity();
},10000);
and here is the code that is called:
function changeGravity(){
var rnd = Math.floor((Math.random() * 4) + 1);
var dir = direction[rnd];
gravity.direction = dir;
}
When ran, the interval lasts for 10 seconds before executing, however once executed it does not stop. What I'm looking for is for it to execute only once every 10 seconds.
Thanks for your help! :)
Upvotes: 1
Views: 3283
Reputation: 31
I dealt with this repeated set interval call recently.
If you want to run it only once for the duration, do the following.
Create a global variable:
MyInterval = null;
Then, wherever you want to start this gravity check for the first and only time, do the following:
if (MyInterval == null)
{
MyInterval = setInterval(function() {
changeGravity();
}, 10000);
}
So, initially the interval variable will be null
, then it will become assigned, then the interval code will never run again because the variable is no longer null
.
Upvotes: 2
Reputation:
You don't show the code for the draw()
function but logic should dictate that this is a method you need to call more than one time.
The setInterval()
will run until a clearInterval is used on it. It will run a new "instance" each time it is called so every time you call draw()
it will add a new timer.
You either want to move the invocation of setInterval()
outside the draw()
method and make sure it will be called only once when needed (remember to store the timer ID for it so you can stop it later).
var timerID = setInterval(changeGravity, 10000);
and when you want to stop it:
clearInterval(timerID);
Or you will want to use setTimeout()
instead which triggers the target code only once after the timeout. This will however not be called every 10th second but only when draw()
is called.
Upvotes: 1
Reputation: 2298
You should care about side effects and other calls of changeGravity
outside. Your current implementation would execute once every 10 seconds, as it says. You should care of the scope of all variables. As an optimization, you have no need to wrap changeGravity
into another function. You can just pass its reference, taking account it is a first class function:
setInterval(changeGravity, 1000);
Upvotes: -1