when it has wholly crossed a goal line or touch line, whether on the ground or in the air, or

when play has been stopped by the Referee.

Once the Referee has decided to stop play for an infringement that has occurred, the ball is out of play from that time, even though some slight interval may elapse before the Referee blows the whistle. Since lines belong to the areas of which they are the boundaries, the touch lines and the goal lines belong to the field of play. So, the ball is in play if any part of it is on or over one of these lines.
The ball is in play at all other times, from the start of the match to the finish, including when:

it rebounds from a goal post, crossbar, or corner flag post and remains in the field of play;

it touches the Referee when in the field of play.

If an outside agent (e.g., a dog, spectator, loose ball, etc.) enters the field and interferes with play, the Referee shall stop the match and restart play with a dropped ball at the place where the contact or interference occurred (subject to Law 8), even if the interruption of play severely disadvantages one team (e.g., if the ball is about to enter the goal).