That's why I asked for an advice, that's an empiric solution that barely worked better. I tried before with a while loop, but it wasn't much different.
Because the code works fine, but seems to ignore the time condition at the restart if the state change is too fast, counts just fine tho.