Capture Joystick Direction Accurately

I’m trying to use the joystick (and keyboard keys) to select a direction without actually travelling in said direction. For example, I want to point an arrow in a direction using the joystick. However, when I release the joystick, I want the arrow to remain in that direction without changing. Here’s the code I’ve come up with so far (in JavaScript):

var dir : Vector3;
var randomObject : Transform;

function Update()
{
    var horiz = Input.GetAxis("Horiz");
    var vert = Input.GetAxis("Vert");
    // Check that they're not BOTH zero - otherwise
    // dir would reset because the joystick is neutral.
    if(horiz != 0 || vert != 0))
    {
        dir.x = horiz;
        dir.z = vert;
        dir.Normalize();
    }
    randomObject.position = dir;
}

This works when going up, right, down, or left. It also works when I press a diagonal direction; however, when I release the keys or joystick, it’s pretty much random whether it stays that direction or heads off to the left or right. I know it’s just a matter of processing the input correctly, but I’m at a loss as to how to do this. Any ideas?

I don’t care what programming language an answer is in, and I’ll try to keep working this out myself.

So, I ended up solving this by adding a ‘timing’ dead zone - a small grace period for the user if they’re transitioning AWAY from a diagonal value. I have yet to fully test it with a joystick, but it works with WASD quite nicely.

var timeDeadZone = 0.0;
var dir : Vector3;

function Update()
{
    var moveHoriz = Input.GetAxis("MoveHoriz");
    var moveVert = Input.GetAxis("MoveVert");
    // If one of them's not zero, set moveDir
    if(moveHoriz != 0 || moveVert != 0)
    {
        // If we're coming from a diagonal direction, wait for a bit
        if(Mathf.Abs(moveDir.x) > 0 && Mathf.Abs(moveDir.z) > 0 && currTimeDead <= 0)
            currTimeDead = 0.1;

        if(currTimeDead > 0)
            currTimeDead -= Time.deltaTime;

        // If we're done waiting, set the direction
        if(currTimeDead <= 0)
        {
            moveDir.x = moveHoriz;
            moveDir.z = moveVert;
            moveDir.Normalize();
        }
    }
}

Thanks to those who answered for taking time to do so, though!

You simply need a dead zone. At the moment you only have a “dead point” which is 0,0. If you release the stick one axis will probably reach 0 before the other or bounce around 0 for a short moment. This will result in a more or less random last result when both axis reach 0. The solution is to create a dead zone:

var dir : Vector3;
var randomObject : Transform;
var deadZone = 0.2;

function Update()
{
    var horiz = Input.GetAxis("Horiz");
    var vert = Input.GetAxis("Vert");
    var tmp = Vector3(horiz, 0, vert);
    if(tmp.sqrMagnitude > deadZone)
    {
        dir = tmp.normalized
    }
    randomObject.position = dir;
}