Moved $direction variable inside the timer function