JSFiddle - React, Tailwind, and code Playground
HTML
<div id='anim'>Click to animate</div>
CSS
#anim {
position: absolute;
top: 500;
left: 0;
width: 100px;
height: 100px;
background-color: #ddd;
padding: 5px;
}
JavaScript
var duration = 1000; // in ms
var startTime; // in ms
var startX = 0;
var endX = 500;
// 0 means try to get as many frames as possible, otherwise the update rate in ms
// Remember that this is not guaranteed to run as often as requested
var refreshInterval = 0;
var div = document.getElementById('anim');
function updatePosition() {
var now = (new Date()).getTime();
var msSinceStart = now - startTime;
var percentageOfProgress = msSinceStart / duration;
var newX = (endX - startX) * percentageOfProgress;
div.style.left = Math.min(newX, endX) + "px";
if (window.console) {
console.log('Animation Frame - percentageOfProgress: ' + percentageOfProgress + ' newX = ' + newX);
}
if (newX < endX) {
scheduleRepaint();
}
}
function scheduleRepaint() {
setTimeout(updatePosition, refreshInterval);
}
div.onclick = function() {
startTime = (new Date()).getTime();
scheduleRepaint();
}
//Initialize the animation, setting the delay to 0 makes sure it gets the best possible
// refresh rate