We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi there, I was experimenting with a timer, but I can't understand why the timer starts automatically even without callling the function start(); And I can't manage to have the timer to start only when I ask it to start.
Timer timer;
void setup() {
size(200,200);
background(0);
timer = new Timer(5000);
//timer.start();
}
void draw() {
if (timer.isFinished()) {
background(random(255));
timer.start();
}
}
// Timer Class
class Timer {
int savedTime;
int totalTime;
Timer(int tempTotalTime) {
totalTime = tempTotalTime;
}
void start() {
savedTime = millis();
}
boolean isFinished() {
int timePassed = millis() - savedTime;
if (timePassed > totalTime) {
return true;
} else {
return false;
}
}
}
Any int? Thank you very much!
Answers
highlight code, press ctrl-o. it's unreadable otherwise.
what are you initialising start to?
(you aren't, so it'll be 0...)
Sorry I don't understand what you mean "what are you initialising start to?" I am calling timer.start(); BUT even without the function call, the timer stars anyway....
The first call to
if (timer.isFinished())
is starting the timer, before you get to timer.startoh, the method is start() the variable is savedTime.
savedTime is not initialised, so it's 0. line 33 is using this uninitialised value and will be true after 5000ms.
maybe initialise savedTime to -1 to denote that the timer isn't started and then add a check for this in isfinished()
there are also 3 different libraries that do countdown timers listed on the libraries page, there's no reason to write your own.
https://processing.org/reference/libraries/ (under Utilities)
https://forum.Processing.org/two/discussions/tagged/timertask
Thanks everyone for helping!
Maybe none need this but, if it can be useful to somebody, here you have my timer, starting and working automatically or by pressing the mouse button. Pretty sure there are better ways to do it but still, it works fine for me! ;)