As others have mentioned, taking a step back and trying to have in mind the end goal help me get on track. I also try to break the task in smaller steps, either mentally or on a notepad, where I outline the steps I have in mind.
I noticed that it usually happens to me when I'm overwhelmed with the task.