What would be the best way to flag a sudden change in movement direction?

I need some help in how to script this, or at least, the values I need to get to pull this off.

What I want to do is make it so that if the player is running forward and they decide all of a sudden to run backwards and move in the opposite direction, an animation will play of the character transitioning into that direction. I attached a still of the animation to help convey the idea.

I was think of having an integer that counts up while the forward direction [W] is held up to say, 5. When the player releases the movement button, it slowly drops to zero. If the player is at a count of 3 or more holding [W] and quickly presses down back [S], the animation will play. My question is, what would be the most efficient way to pull off this sort of system?