進度條是常見的載入回饋元件。在不引入任何庫的前提下,用原生 JavaScript 配合一點 CSS 就能實現。本文提供兩套完整可執行的實現,並比較定時器方案的差異。
思路是每次呼叫讓進度條寬度增加 1%,遞迴調用 setTimeout 直到達到 100%。
<html>
<head>
<title>進度條</title>
<style type="text/css">
.container{ width:450px; border:1px solid #6C9C2C; height:25px; }
#bar{ background:#95CA0D; float:left; height:100%; text-align:center; line-height:150%; }
</style>
<script type="text/javascript">
function run(){
var bar = document.getElementById("bar");
var total = document.getElementById("total");
bar.style.width = parseInt(bar.style.width) + 1 + "%";
total.innerHTML = bar.style.width;
if(bar.style.width == "100%"){
window.clearTimeout(timeout);
return;
}
var timeout = window.setTimeout("run()", 100);
}
window.onload = function(){
run();
}
</script>
</head>
<body>
<div class="container">
<div id="bar" style="width:0%;"></div>
</div>
<span id="total"></span>
</body>
</html>
效果圖:

實現要點有三處:容器 .container 提供邊框作為進度槽,內部 #bar 通過百分比寬度表現進度;`parseInt(bar.style.width)` 把 "5%" 這樣的字串取出數值部分;到 100% 時清除計時器並 return,避免繼續遞迴。
用週期性計時器可以省掉手動遞迴,程式碼更扁平。
<html>
<head>
<title>進度條</title>
<style type="text/css">
.processcontainer{ width:450px; border:1px solid #6C9C2C; height:25px; }
#processbar{ background:#95CA0D; float:left; height:100%; text-align:center; line-height:150%; }
</style>
<script type="text/javascript">
function setProcess(){
var processbar = document.getElementById("processbar");
processbar.style.width = parseInt(processbar.style.width) + 1 + "%";
processbar.innerHTML = processbar.style.width;
if(processbar.style.width == "100%"){
window.clearInterval(bartimer);
}
}
var bartimer = window.setInterval(function(){ setProcess(); }, 100);
</script>
</head>
<body>
<div class="processcontainer">
<div id="processbar" style="width:0%;"></div>
</div>
</body>
</html>
效果圖:

setTimeout() 只執行一次;若要重複執行,必須在回調內部再次呼叫自己。setInterval() 則會按固定間隔週期性執行,直到被 clearInterval() 取消或視窗關閉。
兩者的選擇取決於語義:需要「延遲一次執行」用 setTimeout;需要「固定節拍輪詢」用 setInterval。但要注意,setInterval 不會等待回調執行完畢就開始下一輪,若回調耗時超過間隔,任務會堆積。這種情況更推薦用「setTimeout 遞迴」模式,它天然保證了上一次執行結束後才排下一次。
1. 動畫類效果優先考慮 CSS transition,把 width 的變化交給 GPU 合成,比 JS 定時改樣式更流暢。
2. 若進度來自真實的非同步任務(檔案上傳、資料載入),應由進度事件驅動,而非用計時器「假裝」前進。
3. 定時器 id 務必保存下來,在任務結束或元件銷毀時清理,避免記憶體洩漏與幽靈更新。