
原代碼使用 for 循環創建 100,000 個 setTimeout,每 2 秒切換一次邊框顏色。這種寫法存在嚴重問題:
setTimeout("string") 存在安全隱患且難調試<style>
@keyframes rotateBorder {
0% { border-left-color: red; border-bottom-color: green; border-right-color: yellow; border-top-color: blue; }
25% { border-left-color: blue; border-bottom-color: red; border-right-color: green; border-top-color: yellow; }
50% { border-left-color: yellow;border-bottom-color: blue; border-right-color: red; border-top-color: green; }
75% { border-left-color: green; border-bottom-color: yellow;border-right-color: blue; border-top-color: red; }
100% { border-left-color: red; border-bottom-color: green; border-right-color: yellow; border-top-color: blue; }
}
.rotating-ring {
width: 100px;
height: 100px;
border: 40px solid;
border-radius: 50%;
animation: rotateBorder 8s linear infinite;
background: #fff;
}
</style>
<div class="rotating-ring"></div>
<script>
const colors = [
{left: 'red', bottom: 'green', right: 'yellow', top: 'blue'},
{left: 'blue', bottom: 'red', right: 'green', top: 'yellow'},
{left: 'yellow',bottom: 'blue', right: 'red', top: 'green'},
{left: 'green', bottom: 'yellow',right: 'blue', top: 'red'}
];
let index = 0;
let animationId = null;
const $ring = $('#div1');
function animate() {
const c = colors[index % 4];
$ring.css({
'border-left-color': c.left,
'border-bottom-color': c.bottom,
'border-right-color': c.right,
'border-top-color': c.top
});
index++;
animationId = requestAnimationFrame(animate);
}
// 控制函數
function start() { if (!animationId) animate(); }
function stop() { cancelAnimationFrame(animationId); animationId = null; }
function setSpeed(ms) { /* 需配合 setInterval 實現 */ }
// 啟動
start();
</script>
let idx = 0;
const timer = setInterval(() => {
const c = colors[idx++ % 4];
$('#div1').css({
'border-left-color': c.left,
'border-bottom-color': c.bottom,
'border-right-color': c.right,
'border-top-color': c.top
});
}, 2000); // 每 2 秒切換
// 停止:clearInterval(timer)
#div1 {
width: 100px;
height: 100px;
border: 40px solid;
border-left-color: red;
border-right-color: yellow;
border-bottom-color: green;
border-top-color: blue;
background: #fff;
border-radius: 90px; /* 50% 也可 */
}
關鍵點:border-radius: 90px 將正方形變圓,寬高 100px + 邊框 80px = 實際直徑 260px,半徑 130px,90px 略小形成「環」狀。
| 方案 | 性能 | 可控性 | 兼容性 | 推薦場景 |
|---|---|---|---|---|
| CSS Animation | ★★★★★ | ★★☆☆☆ | IE10+ | 純展示、無需交互控制 |
| requestAnimationFrame | ★★★★☆ | ★★★★★ | IE10+ | 需精確控制、配合其他動畫 |
| setInterval | ★★★☆☆ | ★★★☆☆ | 全瀏覽器 | 簡單輪播、老項目維護 |
| 原始 10 萬 setTimeout | ★☆☆☆☆ | ☆☆☆☆☆ | 全瀏覽器 | 絕不推薦 |
旋轉彩圈效果應優先使用 CSS Animation,既高效又簡潔。若需 JS 控制,requestAnimationFrame 或 setInterval 均優於原始的海量 setTimeout 方案。實際開發中,務必避免創建大量無法管理的定時器。