Frontend Development 12 min read

Master Simple Easing: Plug‑and‑Play Animation Algorithm for UI

This article introduces a lightweight easing algorithm that moves an element by half the remaining distance each frame, provides a requestAnimationFrame polyfill, a reusable Math.easeout function, and shows real‑world usage in Qidian's scroll‑to‑top and other UI effects.

Yuewen Frontend Team
Yuewen Frontend Team
Yuewen Frontend Team
Master Simple Easing: Plug‑and‑Play Animation Algorithm for UI

After a whimsical story, the article introduces a simple easing algorithm for UI animations, where the position moves by half the remaining distance each frame.

The basic formula is:

<code>A = A + (B - A) / 2</code>

In words: next position = current position + half of the distance to the target.

A requestAnimationFrame polyfill ensures compatibility:

<code>if (!window.requestAnimationFrame) {
    requestAnimationFrame = function(fn) {
        setTimeout(fn, 17);
    };
}</code>

The generalized version uses a variable rate:

<code>A = A + (B - A) / rate</code>

A reusable function Math.easeout is provided:

<code>Math.easeout = function(A, B, rate, callback) {
    if (A == B || typeof A != 'number') return;
    B = B || 0;
    rate = rate || 2;
    var step = function() {
        A = A + (B - A) / rate;
        if (A < 1) {
            callback(B, true);
            return;
        }
        callback(A, false);
        requestAnimationFrame(step);
    };
    step();
};</code>

Example usage for a “back‑to‑top” animation:

<code>var doc = document.body.scrollTop ? document.body : document.documentElement;
Math.easeout(doc.scrollTop, 0, 4, function(value) {
    doc.scrollTop = value;
});</code>

The same algorithm powers various effects on the Qidian mobile site, such as the scroll‑to‑top button, the “recently read” ball movement, and page‑turning animations.

frontendanimationuiJavaScriptrequestAnimationFrameeasing
Yuewen Frontend Team
Written by

Yuewen Frontend Team

Click follow to learn the latest frontend insights in the cultural content industry. We welcome you to join us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.