How can I fix my Timer Bug?

the first second the timer does not work. is there any way to fix it? also is there a way to make it mor compact?

String milliseconds;
int second;
int timer;
int index;

void setup() {
  size(500, 500);
}

void draw() {
  milliseconds = str(millis()); // Puts millisecods in a String
  second = int(milliseconds.charAt(index)); // Always looks at the three-digit position from behind. The digit with the number of seconds
  timer = second % 2; // looks if there is a leftover in the division of second / 2. The acctual timer
 
  if (timer == 1) { // if there is a leftover, the background is turned to white
    background(0);
  }

  if (timer == 0) { // if there isnt a leftover, the background is turned to black
    background(255);
  }

  if (milliseconds.length() == 4) {   // whenever the length of the string changes, the position to be looked at is also changed, so that the second digit is always looked at
    index = 0;
  }

  if (milliseconds.length() == 5) {
    index = 1;
  }

  if (milliseconds.length() == 6) {
    index = 2;
  }

  if (milliseconds.length() == 7) {
    index = 3;
  }

  if (milliseconds.length() == 8) {
    index = 4;
  }

  if (milliseconds.length() == 9) {
    index = 5;
  }

  if (milliseconds.length() == 10) {
    index = 6;
  }

  if (milliseconds.length() == 11) {
    index = 7;
  }

  if (milliseconds.length() == 12) {
    index = 8;
  }
}

Maybe I misunderstand, what you try to do, but why don’t you do:

leftover = int(seconds/2) - (seconds/2)

If leftover is not zero, then white, if it is zero, then black.

You shouldn’t check for exactly leftover == 0, because there might be rounding errors.

Hello,

Consider this:

println(millis()/1000); // integer math

You can use:

println()

statements in your code to see the state of the variables.
It helps.

:)