How to create a function that slides an element right a certain distance over a certain duration

Here is one way to create a function that slides an element right a certain distance over a certain duration.

An interactive Stackblitz can be found here.

slideRightTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const element = document.getElementById('square');
let startTime,
distance = 100,
duration = 2000;
function slideRight(timestamp, element, distance, duration) {
timestamp = timestamp || (new Date()).getTime();
const runtime = timestamp - startTime;
const progress = runtime / duration;
const nextPosition = (progress * distance).toFixed(2);
element.style.transform = `translateX(${nextPosition}px)`;
if (runtime < duration) {
requestAnimationFrame((timestamp) => {
slideRight(timestamp, element, distance, duration)
})
} else {
// only used to reset and loop
element.style.transform = `translateX(0px)`;
requestAnimationFrame((timestamp) => {
startTime = timestamp || (new Date()).getTime();
slideRight(timestamp, element, distance, duration);
})
}
}
requestAnimationFrame((timestamp) => {
startTime = timestamp || (new Date()).getTime();
slideRight(timestamp, element, distance, duration);
})