Timer problems

Hello!

I have implemented a timer into my code, however it doesn't work after the third time of repeating itself. For example, I have it countdown from 5, and after the third round, it will jump up to 63 seconds. I have it set as a class. I have made it so you can copy and paste the code and have it run. I've noticed that it also does this when I separated it from my code, so the problem isn't about calling it from the main program.

  int resetAt;
  float c=0;
  float p=0;

void setup(){
  fill(0);
  PFont font;
  font = createFont("Copperplate.ttc", 72);
  textFont(font,72);
  reset();
}

void reset(){
  resetAt = second() + 5;
}

  void draw(){
   fill(0);
  int timeLeft = resetAt - second();
  text(timeLeft, 20, 20);
  println("time left: " + timeLeft);

  if(timeLeft<4){
    println ("time left less than 3: " + timeLeft);
    noStroke();
    fill(0);
    rectMode(CENTER);
    rect(width/2, height/2, 25,30);
    fill(255);
    textMode(CENTER);
    textSize(20);
    int countDown = 1 + (timeLeft / 1);
    if (timeLeft<4){
    text( timeLeft, width/2, height/2);
  }
 }

  if( second() >= resetAt ){
    println ("reset");
    reset();
    background(0);
   }

}

Is there any way to find out what is going wrong?

Tagged:

Answers

  • I noticed it will stop at a certain number, say 9, and then add 60 to it. I don't know if that is of any importance.

  • Answer ✓

    The method second() returns a value 0-59 which means reset can have a value 5-64 (from line 14). Now it reset is ever >= 60 then the conditional statement at line 38 can NEVER be true i.e.

    second() >= reset will always be false

    The answer is not to use the second() method for a timer instead use millis() which measures the time since the sketch started in milliseconds so the reset methos becomes

    void reset(){ resetAt = millis() + 5000; // current time + 5 seconds }

    and line 38 becomes if( millis() >= resetAt ){

  • Thank you so much!

Sign In or Register to comment.