There are some 'misinformation' around this. Penalty shoot outs have their own special cases. But during a game, substitution can happen pretty much any time the ball is not in play. Law 3 sets the procedure.
In fact in an extreme case, after a penalty has been taken and it has to be retake, say due to an encroachment, the defending team can substitute their goalkeeper before the retake.