目標:將元素寬度從 100px 動畫至 200px,歷時 1000ms。
function animate1(element, endValue, duration) {
var startTime = new Date(), startValue = parseInt(element.style.width), step = 1;
var timerId = setInterval(function() {
var nextValue = parseInt(element.style.width) + step;
element.style.width = nextValue + 'px';
if (nextValue >= endValue) {
clearInterval(timerId);
element.innerHTML = new Date - startTime; // 顯示實際耗時
}
}, duration / (endValue - startValue) * step);
}
animate1(document.getElementById('test1'), 200, 1000);
缺陷:setInterval 不保證精確間隔,瀏覽器最小間隔 ~4ms、標籤頁背景節流、系統負載影響,導致實際耗時 ~1500ms (目標 1000ms)。
function animate2(element, endValue, duration) {
var startTime = new Date(), startValue = parseInt(element.style.width);
var timerId = setInterval(function() {
var percentage = (new Date - startTime) / duration;
var stepValue = startValue + (endValue - startValue) * percentage;
element.style.width = stepValue + 'px';
if (percentage >= 1) {
clearInterval(timerId);
element.innerHTML = new Date - startTime;
}
}, 13); // 約 75fps,配合螢幕刷新率
}
animate2(document.getElementById('test2'), 200, 1000);
改進:根據經過時間計算進度,動畫時長固定,不受幀率波動影響。誤差縮減至 ~10-20ms。
function animate3(element, endValue, duration) {
var startTime = new Date(), startValue = parseInt(element.style.width);
var timerId = setInterval(function() {
var percentage = Math.min(1, (new Date - startTime) / duration); // 夾擋上限 1
var stepValue = (percentage >= 1) ? endValue : startValue + (endValue - startValue) * percentage;
element.style.width = stepValue + 'px';
if (percentage >= 1) {
clearInterval(timerId);
element.innerHTML = new Date - startTime;
}
}, 13);
}
兩大修正:
Math.min(1, ...) 防止進度超過 1 (因最後一幀可能超時)。endValue,避免浮點數運算誤差 (如 200.0000001px)。顯示器刷新率通常 60-75Hz → 幀間隔 13-16ms。設 13ms 可盡量對齊螢幕刷新,減少撕裂、提升流暢度。現代瀏覽器提供 requestAnimationFrame (rAF) 自動對齊刷新率。
function animateRAF(element, endValue, duration) {
var startTime, startValue = parseFloat(getComputedStyle(element).width);
function step(timestamp) {
if (!startTime) startTime = timestamp;
var progress = Math.min(1, (timestamp - startTime) / duration);
element.style.width = (startValue + (endValue - startValue) * progress) + 'px';
if (progress < 1) requestAnimationFrame(step);
else element.innerHTML = timestamp - startTime;
}
requestAnimationFrame(step);
}
優勢:
timestamp 為高精度 DOMHighResTimeStamp (微秒級)。// 線性
var linear = t => t;
// 緩入
var easeInQuad = t => t * t;
// 緩出
var easeOutQuad = t => t * (2 - t);
// 緩入緩出
var easeInOutQuad = t => t < 0.5 ? 2*t*t : -1 + (4-2*t)*t;
// 使用
var stepValue = startValue + (endValue - startValue) * easeOutQuad(progress);
| 維度 | CSS | JS (rAF) |
|---|---|---|
| 效能 | GPU 加速、主執行緒不阻塞 | 主執行緒執行,複雜計算可能掉幀 |
| 控制力 | 聲明式、難以動態中斷/回調 | 完全程式化控制、支援複雜邏輯 |
| 適用場景 | 簡單狀態切換 (hover、class toggle) | 遊戲、編輯器、複雜序列、需同步多元素 |
從累加到時間插值、從 setInterval 到 rAF、從線性到緩動,JavaScript 動畫演進史就是「追求時間精確性與視覺自然度」的歷程。理解底層原理,才能在選擇 CSS 或 JS、引入 GSAP/Anime.js 等庫時做出正確架構決策。