Hi,
the millis()
function is the way to go.
The idea is to save the time at which you want to start waiting (imagine starting a chronometer).
Then, you check the time over and over until the new time is passed the waiting time that you wanted.
You can do that like so:
long waitStart = millis();
while (millis() - waitStart < 3000) {
// Do nothing
}
// Do something after the 3 seconds
Now, putting a 3 seconds wait inside an if statement (or your draw()
function for that matter) is probably not the best way to go since you’ll freeze your whole application during that time and it won’t be responsive at all…
You probably want to split your application into different states and use a combination of flags and timer to get the job done.
To illustrate, consider the following exemple:
I want to draw a rectangle on the screen when I click the mouse button for 3 seconds then get rid of it. Your first go might be to do something like this:
boolean showRect = false;
long startWait;
void setup() {
size(800, 600);
background(20);
}
void draw() {
background(20);
if (showRect) {
startWait = millis(); // I start the timer since I just start to draw the rectangle
fill(200, 0, 0);
rect(300, 200, 200, 200);
}
fill(200);
ellipse(mouseX, mouseY, 50, 50);
// I have drawn the rectangle and I'm waiting three seconds
while (millis() - startWait < 3000) {
// Do nothing
}
showRect = false;
}
void mouseClicked() {
showRect = true;
}
You can try, but you won’t even see the rectangle. The reason is that all the elements are beeing drawn only when the draw loop is finished. In this case when you clic, it waits 3 seconds BEFORE finishing it so it is drawing the rectangle only for one frame.
Instead, you should not block the main loop and simply check the time everytime you go trhough that loop like so:
boolean showRect = false;
long startWait;
void setup() {
size(800, 600);
background(20);
}
void draw() {
background(20);
if (millis() - startWait > 3000) {
showRect = false;
}
if (showRect) {
fill(200, 0, 0);
rect(300, 200, 200, 200);
}
fill(200);
ellipse(mouseX, mouseY, 50, 50);
}
void mouseClicked() {
showRect = true;
startWait = millis();
}