This site requires JavaScript, please enable it in your browser!
Greenfoot back
CrazyGamer1122
CrazyGamer1122 wrote ...

2012/9/22

Timer Method?

CrazyGamer1122 CrazyGamer1122

2012/9/22

#
is there a way to time a certain method, like if you want something to happen at a certain time?
danpost danpost

2012/9/23

#
You will need a field to track the passage of time (or act cycles). Set the field in the constructor of whatever class you need the timer in. In the act method of that class check to see if however many seconds (or act cycles) have passed, When passed, call the method. Be careful, however, on how you code it. You do not what the method to be called continuously after the time (or act cycles have passed). The easiest way to do this is using act cycles instead of actual time passed. In the constructor set the timer field to the number of act cycles before calling the method. Each act cycle, first check to see if the timer field is not zero, and then, if not, decrement the timer value and check for zero; and if so, call the method. Something like to following:
1
2
3
4
5
if (timer > 0)
{
    timer--;
    if (timer == 0) methodName();
}
Notice that if the timer is already zero, than nothing will happen (the method will not be called). You could, in the act() method call a method with 'checkTimer();' and have the method look like this:
1
2
3
4
5
6
private void checkTimer()
{
    if (timer == 0) return; // the timer is not in use
    timer--;
    if (timer == 0) methodName();
}
CrazyGamer1122 CrazyGamer1122

2012/9/23

#
thanks for the help, is it possible to make the timer count down in a certain time period (seconds, minutes, etc)?
danpost danpost

2012/9/23

#
Make 'timer' of type 'long' and initialize it to zero. Set timer to 'System.currentTimeMillis()' in the constructor. Instead of
1
2
timer--;
if (timer == 0) methodName();
use
1
2
3
4
5
if (System.currentTimeMillis() - timer >= 1000)
{
    timer = 0;
    methodName();
}
The '1000' represents one second; so multiply it by the number of seconds you wish to delay.
CrazyGamer1122 CrazyGamer1122

2012/9/23

#
thanks for your help :)
JustFusion JustFusion

2015/11/9

#
How would you use a timer if you wanted to switch an image for a couple of seconds?
You need to login to post a reply.