Different behavior of the sketch if Arduino is powered by battery

So you trying to use on-board voltage regulator on your UNO to power the servo? It can't work that way.
You need an external power for the servo motor.