美好的一天!我正在學習JavaScript,並對定時器有問題。我只是想檢查整個頁面寫入後是否觸發onload事件,包括通過javascipt修改的文本。爲此,我想通過在字符之間產生200毫秒的延遲來減慢文字的寫入。如何在for(){}循環中使用setTimeout?
我使用的測試如下:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Onload test</title>
<script>
function load() {
alert("The page is considered loaded !");
}
function writeSlowly(text, timer) {
var L= text.length;
var st = "";
function write (seq) {
document.getElementById("st").innerHTML = seq;
};
for (var i = 0; i < L; i += 1) {
st += text[i];
setTimeout(write(st), timer);
};
};
</script>
</head>
<body>
<p id="st"></p>
<script>
writeSlowly("This pages takes a while to load", 200);
window.onload = load;
</script>
</body>
</html>
頁面加載時不存在任何延遲都可言。實際上,我預計文本(32個字符長)大約需要32 x 200 ms =〜7秒。調試時(使用Firebug - 我使用Firefox 30),程序逐行執行,但計時器無效。該頁面幾乎即時顯示。
可能重複[如何在JavaScript循環中添加延遲?](http://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-循環) – Adam
謝謝亞當,Cheruvian&al。我會進一步練習。 – RAH
謝謝Cheruvian和Adam花時間寫出正確的解決方案。你的腳本都在工作。我會確保我理解它的要點。 – RAH