Loading...
Logo
Processing Forum

how to reset count time

in Programming Questions  •  10 months ago  
I would like to run a program in 5 seconds and then reset the timer back to 0
so the timer will start to count from 0 to 5 seconds again after the new frame..but failed with
the code below..could someone show me what is wrong??

Copy code
  1. void draw(){
  2.   int m = millis();
  3.   println(m);
  4.   if(m == 5000){
  5.     m = 0;
  6.   }
  7. }


Replies(4)

you don't get every millisecond in the draw cycle, because each program cycle needs more than a millisecond. so you should check if m > 5000

and so you just get the first time millis is over 5000. what you wanna do is more like this:

Copy code
  1. int last = 0;
  2. int m = 0;
  3. void draw(){
  4. m = millis()-last;
  5.   if(millis() > last+5000){
  6.       last = millis();
  7.     // do something every 5 seconds 
  8.   }
  9. }
Thank you csteinlehner!! I put the println(m) inside the if to see whats going on..
it outputs number around 5000 so I guess it worked..

but I dont understand the meaning of it..
correct me if I'm wrong here :

1. milliseconds count will start from line 4..
2. in the first iteration(or first frame of draw()??), variable m in line 4 will be 0, then in line 6, variable last would  be something around 5000 and it will always stay as something around 5000(means the one that's increasing would be only millis() but not variable last eventhough last = millis()..) until the next if statement.
3. the millisecond will continue to increase until something around 10000 which will satisfy the if statement and then the variable last will be something around 10000..
4. in conclusion the one that will be inserted in the variable last would be the the milliseconds(from the first iterations) at the time it is defined in line 6..

if this is true, then we could do something every 5 seconds without line 2 and line 4??

I'm sorry for the hard to understand English..I appreciate your help





millis() counts the milliseconds from the start of your program, so it will not be 0 when you call it the first time.
If you want the counter to be very precise, than you should store the value of millis() when draw is executed for the first time in your "last"-variable.
But you are right, "m" is not needed in the code above, you could delete those lines.
got it..
thanks benja for the advice and confirmation..

I hope this post and this would be some help to others with same question