It knows when the keys are released because your logic says when 8 direction is not moving then set the animation to an idle animation. Because you just released for example W then you character will want to face up so it will play the up animation and it will have a variable set related to when W was down.
For the key logic you do something like :
W is down - set variable to 1
D is down - set variable to 3
W is down AND D is down - set variable to 2
You do an AND by adding both conditions together on the same event
Use a global variable, not a local variable.
The idea is when you release a key, the last key or keys that were down will have produced a variable. If you were holding W(up) and released then the variable will be 1 etc. That variable then relates to an animation.