Count no. of cycles.

And remember, don't increment WHILE the condition is true, increment when the condition GOES true.

In the IDE: File/examples/digital/statechangedetection