How to run program for x seconds, pause for x seconds?

Hi, I’m new to processing and I’m trying to figure out a way to run a function, pause for a certain amount of time, then continue running the program. So something like this
-run function 1 for 0.1 seconds
-pause for 0.1 seconds
-continue running function 1 for 0.1 seconds
-pause for 0.1 seconds
continue…

I am not sure exactly how to do this and would appreciate help! Thanks

Hi,

In order to do that, you need to keep track of the time. In Processing you have some functions to deal with time but the useful one in this case is millis().

The millis() function gives you the current time in milliseconds since the beginning of the program. The last part of the sentence is important because other functions as seconds() or minutes() gives you the current time stored by your computer’s clock.

Now you know that the setup() function and the draw() functions are not executed the same way. The setup() function is only executed once at the beginning and the draw() function roughly every 60 times per second.

So if you executed your function 1 for the first time, you need to wait 0.1s for the next call and the draw() function need to run during that period. So every loop you need to check if the timeout is over :

void draw() {
  if (/* it's been 0.1s since the last f1 call*/) {
    // Call my function
  }
}

Notice the since the last function 1 call. We need to store the previous time where we called our function. For the condition, we can use the current time in milliseconds to check if the difference is greater than a certain amount of time.

Use a global variable for that outside the setup :

int lastCallTime = 0;
int pauseTime = 100; // equivalent to 0.1s

void setup() {

}

void draw() {
  int timeSinceLastCall = millis() - lastCallTime;

  if (timeSinceLastCall > pauseTime) {
    // Call our function
  }
}

The last step is to call our function and reset the last time each time. So here is the full program :

int lastCallTime = 0;
int pauseTime = 100; // equivalent to 0.1s

void myFunction() {
  println("Calling my function every " + (pauseTime / 1000.0) + " s");
}

void setup() {

}

void draw() {
  int timeSinceLastCall = millis() - lastCallTime;

  if (timeSinceLastCall > pauseTime) {
    myFunction();

    // The last call is now
    lastCallTime = millis();
  }
}

And that’s all :wink:

4 Likes