When I’m working on a melody I need absolute quiet. That allows me to feel each note as it is being written on the staff paper. The music itself is leading me and I just keep writing what I am hearing.
I will stay in the piano room and keep writing and re-writing until I reach a point where I need to get away from it all, knowing that when I return, the missing melody line will find its way to the staff paper. It never fails. Walk away and come back refreshed to finish.
For me, the only time a composition is done is when it is finally recorded. At that point I know I did my best and I’m ready to work on something new.