I would like to move a div at a perfect constant speed.
The following project shows my implementation
ponent.html
The code used to move is
setInterval(() => {
const currentTop = parseInt(this.movingDiv!.style.top || '0', 10);
this.movingDiv!.style.top = `${currentTop - 1}px`;
}, frameInterval);
It works but have lags, and even more lags and freeze when the browser have other tasks to do on an other page.
I would like to improve the smoothness if possible, and if not, keep the div sync to background music, because it slow down when lagging.
I would like to move a div at a perfect constant speed.
The following project shows my implementation
https://stackblitz/edit/angular-6x9fejz3?file=src%2FAnimationPage%2Fanimationponent.html
The code used to move is
setInterval(() => {
const currentTop = parseInt(this.movingDiv!.style.top || '0', 10);
this.movingDiv!.style.top = `${currentTop - 1}px`;
}, frameInterval);
It works but have lags, and even more lags and freeze when the browser have other tasks to do on an other page.
I would like to improve the smoothness if possible, and if not, keep the div sync to background music, because it slow down when lagging.
Share Improve this question edited Mar 18 at 21:46 Foxhunt asked Mar 14 at 16:51 FoxhuntFoxhunt 9222 gold badges13 silver badges31 bronze badges1 Answer
Reset to default 0What you probably want to do is calculate a frametime delta in each iteration and use that to properly offset the div. The frametime delta is basically just the amount of time that has passed since the last time you moved the div. Use that value as a factor when offsetting the div and it will make sure the div moves at a constant rate.
This doesn't get rid of any potential lag, it just makes sure that the div moves the same amount of pixels per unit of time. (When there is a lag, the frametime delta is higher, thus the div offset is larger, cancelling out the lag).
An example implementation would be:
let previousTime = Date.now();
while (true) { // your application loop
let now = Date.now();
let delta = now - previousTime; // this is the number of milliseconds since last update
// I lifted this from your example
const currentTop = parseInt(this.movingDiv!.style.top || '0', 10);
this.movingDiv!.style.top = `${currentTop - (delta / 1000) * velocity}px`; // make sure to tweak the velocity, i like to convert the delta to seconds
previousTime = now;
}