- Home /
Call function only if last call was >= X seconds ago
What is the best way to check if the function has already been called in the last X seconds?
Is increasing a Variable each second good for performance? Or are there better possibilities?
Answer by Dave-Carlile · Feb 07, 2013 at 01:03 PM
Here's a simple example of one way to do this. You track elapsed time by adding time.deltaTime
to a float variable every frame. Once the float variable exceeds your target time (I'm using 10 seconds here, you should make it a constant or store in another variable so it's easily configurable), execute the timed code, and reset the timer back to zero.
float timeSinceLastCall;
void Update()
{
timeSinceLastCall += time.deltaTime;
if (timeSinceLastCall >= 10)
{
// TODO : do timed stuff
timeSinceLastCall = 0; // reset timer back to 0
}
}
If you just want to execute something repeatedly every x seconds, you might also take a look at InvokeRepeating.
Does timeSinceLastCall += time.deltaTime;
add 1 every second? Oh, and how do I do this with javascript?
The Update
function is called every frame. During the frame, time.deltaTime
is the time (in seconds) it took to produce the last frame. So you're adding an elapsed time to the variable. At 60 frames per second time.deltaTime
will be 0.016667 or so. So after 60 frames timeSinceLastCall
will have reached the value of 1 second.
The Javascript for this is pretty close to being identical. You shouldn't have much trouble converting it if you take a look.
Ok, thanks so much. For everyone else: time.deltaTime has to be replaced with Time.deltaTime for javaScript. Thanks again!