# How can I calculate when a spesific amount of time has passed [closed]

I am trying to get something to happen, when a spesific amount of time has passed(in my case it is in secounds). I have tried using this method:

   long elapsed = (System.nanoTime()-startTime)/1000000;
if(elapsed > 1000)
{
score++;
startTime = System.nanoTime();
}


with the starttime beiing initiated in the constructor. But when I attack(part of the game) the app either:
chrashes
the things the game renders dissapears, and everything turns black.

I have tried asking google, but it in general gave me the save way. Any new improved ideas?

• Are you certain that the time related computation is responsible for the crashes? Sep 10 '15 at 18:02
• Do you use startTime somewhere else, especially when dividing? Sep 10 '15 at 18:06
• The startTime is only used for this calculation(otherwise, it would not work). Also, i am 100% positive it is this that caused the chrash(removed the calculation and the app worked)
– user69046
Sep 12 '15 at 10:45
• Unrelated to your crash, for regular timers you should use startTime += 1000000000;. When you use startTime = System.nanoTime(); your timer will slowly accumulate error every update because now is always a little bit after your timer expires. Sep 30 '15 at 19:00

what kind of crash does it give you? have you tried to see if the

    (System.nanoTime() - startTime)


could be responsible?

try outputing it to the console with a

    System.out.printLn(System.nanoTime() - startTime);


also try outputing your elapsed variables and make sure it's not Null.

having a peak at the part of the code that causes the crash (you talked about attacking) might help. right now your code seems quite fine to me so taking it out of context is hard to debug.