Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"blinking" boolean with system.currentTimeMillis()

Tags:

java

Why is this value always true? I just can't figure out how to have a boolean that "blinks" every second.

long millis = System.currentTimeMillis();
boolean blink = (Math.floor(millis/1000 + 0.5)==Math.floor(millis/1000));
like image 615
CookieMonster Avatar asked May 22 '26 08:05

CookieMonster


1 Answers

This is how I'd do it

  long millis = System.currentTimeMillis();
  boolean blink = (millis % 2000) < 1000;

This uses the modulo % operator to determine how far into a repeating two second window the current time is. Then it sees if it's in the first half (0 to 999) of the window or the second half (1000 to 1999). This will result in a boolean value that alternates true and false every second.

like image 169
Jim Blackler Avatar answered May 24 '26 20:05

Jim Blackler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!