Why is my code stuck in a looping sequence and not triggering events?