Skip to the code

Animate with transform

When a tea goes into the basket, a badge slides across the top of the menu. Write animateX(element, { from, to, duration, easing }), which moves element horizontally from from to to pixels over duration ms, and returns a promise that resolves, with undefined, when it's done. The JavaScript question How do you animate with requestAnimationFrame, and why is it better than setInterval? (animate-with-requestanimationframe) covers the frame loop; this problem is about what each frame changes.

Move it with element.style.transform, set to "translateX(<x>px)", and change nothing else: no left, no margin-left. A change to left makes the browser lay the page out and paint again in every frame. A change to transform skips layout, and for an element on a layer of its own (will-change: transform in the stylesheet) it skips paint too: the compositor moves pixels it already has. It can't cause a layout shift either.

Run in animation frames, and work out the position from each frame's timestamp, never from how many frames have run. The first frame's timestamp is the start, and in each frame the progress is (timestamp - start) / duration, at most 1. The position is from + (to - from) * easing(progress), where easing is linear, (t) => t, unless given. When the progress reaches 1, set exactly translateX(<to>px), whatever the easing gives, resolve, and ask for no more frames. A duration of 0 or less jumps to the end in the first frame.

const easeOut = (t) => 1 - (1 - t) * (1 - t);
await animateX(badge, { from: -120, to: 0, duration: 300, easing: easeOut });
// badge.style.transform is now "translateX(0px)"

What the tests check

  1. moves the element with transform, one step per frame, and stops at the end
    const clock = useFakeTimers();
    const badge = document.getElementById("badge");
    let finished = false;
    animateX(badge, { from: 0, to: 200, duration: 128 }).then(() => (finished = true));
    const steps = [];
    for (let frame = 0; frame < 10; frame++) {
      clock.tick(16);
      steps.push(badge.style.transform);
    }
    await flush();
    expect(steps).toEqual(["translateX(0px)", "translateX(25px)", "translateX(50px)", "translateX(75px)", "translateX(100px)", "translateX(125px)", "translateX(150px)", "translateX(175px)", "translateX(200px)", "translateX(200px)"]);
    expect(finished).toBe(true);
    
  2. uses the easing it's given
    const clock = useFakeTimers();
    const badge = document.getElementById("badge");
    animateX(badge, { from: 0, to: 200, duration: 128, easing: (t) => t * t });
    const steps = [];
    for (let frame = 0; frame < 9; frame++) {
      clock.tick(16);
      steps.push(badge.style.transform);
    }
    expect(steps).toEqual(["translateX(0px)", "translateX(3.125px)", "translateX(12.5px)", "translateX(28.125px)", "translateX(50px)", "translateX(78.125px)", "translateX(112.5px)", "translateX(153.125px)", "translateX(200px)"]);
    
  3. ends exactly at the target whatever the easing gives, resolves, and asks for no more frames
    const clock = useFakeTimers();
    const badge = document.getElementById("badge");
    let frames = 0;
    const realFrame = requestAnimationFrame;
    globalThis.requestAnimationFrame = (callback) => {
      frames += 1;
      return realFrame(callback);
    };
    const result = await (async () => {
      const done = animateX(badge, { from: 0, to: 200, duration: 64, easing: (t) => Math.min(t, 0.9) });
      await clock.runAllAsync();
      return done;
    })();
    expect(result).toBe(undefined);
    expect(badge.style.transform).toBe("translateX(200px)");
    const asked = frames;
    await clock.runAllAsync();
    expect(frames).toBe(asked);
    expect(asked).toBe(5);
    
  4. works out the position from the frame's time, so a slow frame doesn't slow the animation
    const clock = useFakeTimers();
    const badge = document.getElementById("badge");
    animateX(badge, { from: 0, to: 200, duration: 128 });
    clock.tick(16);
    clock.tick(16);
    clock.tick(16);
    expect(badge.style.transform).toBe("translateX(50px)");
    // A 40 ms long task: the next frame comes late, at 88 ms, 72 ms after the start.
    clock.spend(40);
    clock.tick(1);
    expect(badge.style.transform).toBe("translateX(112.5px)");
    
  5. changes only the transform, never left or margins
    const clock = useFakeTimers();
    const badge = document.getElementById("badge");
    const done = animateX(badge, { from: 0, to: 200, duration: 128 });
    await clock.runAllAsync();
    await done;
    expect(badge.style.left).toBe("");
    expect(badge.style.marginLeft).toBe("");
    expect(badge.getAttribute("style")).toBe("transform: translateX(200px);");
    
  6. a duration of 0 jumps to the end in the first frame
    const clock = useFakeTimers();
    const badge = document.getElementById("badge");
    let finished = false;
    animateX(badge, { from: 0, to: 80, duration: 0 }).then(() => (finished = true));
    expect(badge.style.transform).toBe("");
    clock.tick(16);
    await flush();
    expect(badge.style.transform).toBe("translateX(80px)");
    expect(finished).toBe(true);
    
  7. moves left as well as right
    const clock = useFakeTimers();
    const badge = document.getElementById("badge");
    animateX(badge, { from: 120, to: -40, duration: 64 });
    const steps = [];
    for (let frame = 0; frame < 5; frame++) {
      clock.tick(16);
      steps.push(badge.style.transform);
    }
    expect(steps).toEqual(["translateX(120px)", "translateX(80px)", "translateX(40px)", "translateX(0px)", "translateX(-40px)"]);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).