The question is how to get the train to return to the starting position by the second click. The animation in this case is drawn from 0 to 400px to the left. I need a second click so that it draws from 400px to 0, thus the train returns to its starting position. And why in this animation the train does not always reach a value of 400px, and how we can achieve accuracy when using this function.
train.onclick = function() { var start = Date.now(); // сохранить время начала var timer = setInterval(function() { // вычислить сколько времени прошло из opts.duration var timePassed = Date.now() - start; train.style.left = timePassed / 5 + 'px'; if (timePassed > 2000) clearInterval(timer); }, 20); } #train { position: relative; cursor: pointer; } <!DOCTYPE HTML> <html> <head> </head> <body> <img id="train" src="https://js.cx/clipart/train.gif"> </body> </html>