Skip to content Skip to sidebar Skip to footer

Simple Animation With Javascript Interval

I'm set up a simple animation with set Interval. But I wanted to do an animation where it moves to a target position over time. I used to this back in the flash days and have for

Solution 1:

Using setInterval() isn't the best choice for animations since it cannot sync to monitor updates. A better choice, and highly recommended, is requestAnimationFrame().

Right now the code uses an interval of 5ms which is way too low. The shortest frame update happens at 16.7ms (at 60Hz screens) so there is much overhead here.

I would also suggest using linear interpolation (AKA lerp) to do the animation, and time duration to define speed. Using interpolation allows you to further feed the t into an easing function.

Example

  • t is calculated based on start-time, current time and duration
  • t, now normalized to [0, 1] is fed to lerp function to obtain new position
  • translateX is used to move div to allow subpixeled animation. Final position can still be set by removing translation and a fixed position for left.

var reqId,                                      // request ID so we can cancel anim.
    startTime = 0,
    source = 0,
    target = 300, 
    duration = 1000,                            // duration in ms
    sq = document.querySelector("div");
    
document.querySelector("button").onclick = function() {
  startTime = 0;                                // reset time for tcancelAnimationFrame(reqId);                  // abort existing animation if any
  reqId = requestAnimationFrame(loop);          // start new with time argumentfunctionloop(time) {
    if (!startTime) startTime = time;           // set start time if not set already
    t = (time - startTime) / duration;          // calc tvar x = lerp(source, target, t);            // lerp between source and target position
    sq.style.transform = "translateX("+x+"px)"; // use transform to allow sub-pixelingif (t < 1) requestAnimationFrame(loop);     // loop until t=1// else { here you can remove transform and set final position ie. using left}
  }
  
  // basic linear interpolationfunctionlerp(v1, v2, t) {return v1 + (v2-v1) * t}
};
div {position:absolute; left:0; top:40px; width:100px;height:100px;background:#c33}
<button>Animate</button><div></div>

Post a Comment for "Simple Animation With Javascript Interval"