Why this JavaScript function sometimes takes good value and works, and sometimes not? Probably a problem with refresh rate of the page

I’m trying to animate a snake composed of segments.
These segments should retreat when the mouse is stopped.
So I’m calculating the distance and when the mouse is stopped, I’m changing the position and also the opacity value.
Sometimes it works in a good and smooth way, sometimes not.
This is the code of the function:

function animateSnake() {
    let previousX = mouseX;
    let previousY = mouseY;


    segments.forEach((segment, index) => {
        const dx = previousX - segment.x;
        const dy = previousY - segment.y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance >= segmentSize) {
            const angle = Math.atan2(dy, dx);
            segment.x = previousX - Math.cos(angle) * segmentSize;
            segment.y = previousY - Math.sin(angle) * segmentSize;
        }else if (Date.now() - lastMouseMoveTime > 300) {
            const head = segments[0];
            const angleToHead = Math.atan2(head.y - segment.y, head.x - segment.x);
            if (index != 0) {
                segment.x += Math.cos(angleToHead) * segmentSize / 2;
                segment.y += Math.sin(angleToHead) * segmentSize / 2;
                segment.element.style.opacity = 0;
            }
        }else {
            if (index != 0){
                segment.element.style.opacity = 1;
            }
        }

        segment.element.style.transform = `translate(${segment.x}px, ${segment.y}px)`;

        previousX = segment.x;
        previousY = segment.y;
    });


    requestAnimationFrame(animateSnake);
}

I tried to debug but I could only see that the value were highlighted, but not changed.