You never tell your script to stop incrementing the position of the baseball. To do this, have a boolean as a flag as to whether to increase the baseball or not. An example of this would be
var flag = true;
if (flag)
{
//do something, and eventually set flag to false
flag = false;
}
else
{
//do something else
}
In this instance, you would stop incrementing when the flag is false, and begin incrementing then. I would read this question even though it is in VB because it will help you understand the concept behind this behavior.
EDIT
What I mean when you start/stop the increment, is when you are changing the position of the ball. I have a fiddle showing what is happening. The main error you were getting was that you would move the baseballX back, then forward, then back, etc. I fixed this using the flag, and in your throwBack
function, you reset baseballX
to -350. Some pseudocode of what was happening is like:
while (true)
{
pitch();//1st time: move the ball backwards; 2nd time: the ball's X is greater than -350, so move back until it is less
if (ballX < -350)
{
throwBack();//1st time: resets the ball position to -350, and moves forward; 2nd time: the ball is below so move forward, rinse and repeat
}
}
The flag enabled us to do
while (true)
{
if (!baseballBack)
pitch();//1st time: move the ball backwards; 2nd time: flag tells us to stop pitching
if (ballX < -350 || baseballBack)
{
baseballBack = true;
throwBack();//1st time: resets the ball position to -350, and moves forward; 2nd time: the flag is true, so continue to execute.
}
}