Enemy Animation to not stop when player runs out of range

When my player runs within range of an enemy the enemy performs his attack animation. However if I run out of range while the animation is being performed he stops doing the animation. I want him to play through the entire animation instead of stopping like he currently does. I’m sure it’s something simple but I’m at a loss after trying several things… here is my code if anyone has any suggestions:

    #pragma strict
var target : Transform;
var pirate: GameObject;
var detectRange : float = 30;
var rotateSpeed : float = 10;
private var inRange = false;

function Start () {
pirate.animation.Play("PirateIdle");
pirate.animation["PirateStrike"].wrapMode = WrapMode.Once;
pirate.animation["PirateIdle"].wrapMode = WrapMode.Loop;
}

function Update () {

var hit : RaycastHit;
        var tgtDirection = target.position - transform.position;
        var tgtDistance = tgtDirection.magnitude; // get distance to the target
        if(Physics.Raycast(transform.position,tgtDirection , hit)) {
           if (tgtDistance <= detectRange){
           inRange = true;}
			if (inRange) {
            PirateStrike();
            }
            if (!inRange) {
            pirate.animation.Play("PirateIdle");
            }
          }  
          }
            

function PirateStrike() {
 			var tgtDirection = target.position - transform.position;
			tgtDirection.y = 0;
            pirate.animation.Play("PirateStrike");
            yield WaitForSeconds(1);
           
            var rotate = Quaternion.LookRotation(tgtDirection);
			transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * rotateSpeed);
            }

if (tgtDistance <= detectRange) { // If in the range then attack,
//no need of a bool here
PirateStrike();
}
else if (tgtDistance >= detectRange && !animation.IsPlaying(“PirateStrike”) ) {
pirate.animation.Play(“PirateIdle”);
}

You can try something like this. The if inside checks if you are out of range and if the animation is not playing meaning that if playing the idle animation is not launched.
Also, I put an else if since if you are out of range or in range there is no need for checking the other one.