本文示範如何用原生 JavaScript 做出一個逐字顯示內文的小小閱讀器,並提供暫停與繼續兩個控制按鈕。核心概念是把內容存成陣列,再用 setInterval 定時取出下一個字。
Reader 接收內容與三個元素 id,內部保存目前位置 index,並用閉包保住 this 的指向,避免計時器中的 this 變成 window:
function Reader(content, cID, stopID, continueID) {
this.conLoad = document.getElementById(cID);
this.stopBtn = document.getElementById(stopID);
this.continueBtn = document.getElementById(continueID);
this.content = content;
this.index = 0;
var t = this;
this.stopBtn.onclick = (function () {
return function () { t.stopReader(t); };
})(t);
this.continueBtn.onclick = (function () {
return function () { t.continueReader(t); };
})(t);
}
Reader.prototype = {
startReader: function () {
var t = this;
t.toId = setInterval(function () {
if (t.content[t.index]) { t.conLoad.innerHTML += t.content[t.index]; }
t.index++;
if (t.content.length == t.index) {
clearInterval(t.toId);
t.conLoad.innerHTML += "【未完待續】";
}
}, 200);
},
stopReader: function (t) { t.flag = true; clearInterval(t.toId); },
continueReader: function (t) { if (t.flag) t.startReader(); t.flag = false; }
};
每 200 毫秒吐出一個字,index 走到內容尾端時清除計時器並補上「未完待續」。暫停只是把 toId 記下來的計時器清掉,繼續則在 flag 為真時重新啟動。
window.onload = function () {
new Reader(content, "content", "btnStop", "btnContinue").startReader();
};
目前的實作用 innerHTML 累加,若內容含有標籤會被當成 HTML 解析,較安全的做法是改用 textContent。此外把整段文字切成單字陣列會佔用不少記憶體,也可以改成只保存字串並以 index 取字元。若想讓閱讀節奏更自然,還能把 200 毫秒換成依標點調整的動態延遲。