Execute a function for only 10 seconds?


Hi all… I am having some trouble understanding how to correctly trigger a function, that would only last for a specific duration of time:

I am working with ofxCV and would like to trigger an animation function, every time the contour’s velocity is greater than 5 or so…and I would like for that animation function to last for 5 seconds, even after the contour’s velocity as changed…

for (int i = 0; i < contourFinder.size(); i++){
        ofVec2f velocity = toOf(contourFinder.getVelocity(i));
        int velocityX = abs(velocity.x);
        int velocityY = abs(velocity.y);
        if (velocityX > 5 || velocity.y > 5)
            bFluctuate = true;
    if(bFluctuate) {

Above is in my draw function…and then in my fluctuate() function, I manipulate the contour’s polyline and what not, but I am unable to figure out how to have fluctuate() last for a specific duration of time. Once the velocity goes past 5, the fluctuate function continues forever, but I wish for it to stop after 5 seconds…Can any of y’all point me in the direction of how to control durations of functions?

Thanks so much!!!


I’ve also tried

  while (velocityX > 5 || velocity.y > 5)

but that breaks my code…i am obviously missing something here, which is concerning. For example, how would I go about executing a certain function, so long as the velocity is greater than some specific value? Anytime I try to do any while, within my update() or draw(), it crashes my program.


Try this :

if (velocityX > 5 || velocityY > 5)
            bFluctuate = true;


if (velocity.x > 5 && velocity.y > 5)
            bFluctuate = true;
1 Like

While isn’t crashing your program, but it is getting stuck in a loop, which is what “while” does.

While keeps executing the dependent code until the conditions prove false. So unless fluctuate causes the conditions to fail, it will keep executing fluctuate forever until they do, which will keep your program stopped doing that.

So try doing something like Dorald suggested above, combined with something like “if (bFluctuate) fluctuate();”

That will work because it doesn’t keep executing within one call to Update(). The framework will keep calling Update() and Draw() etc, and each time (once per frame) it will fluctuate and draw, which I think is what you want.

Well, if you want it to fluctuate for 10 seconds, then read the time when you want it to start, save it in a variable outside the scope of update(), and then make your condition to fluctuate be a comparison of current time to the started time. e.g. if (currentTime < startTime + tenSeconds) fluctuate();

1 Like

Works like a charm, so simple too. Thanks to both of y’all, seriously, the help is much appreciated!

1 Like

Glad to be able to help!