js 事件迴圈整理
阿新 • • 發佈:2019-01-06
把平時遇到的事件迴圈相關程式碼,整理在一起,方便更好的理解。
參考博文:
https://blog.csdn.net/duola8789/article/details/83314880
1. setTimeout 中的document.write
先看程式碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM載入順序</title>
</head>
<body>
< p>1</p>
<script>
document.write('2')
</script>
<p>3</p>
<script>
window.onload = function () {
document.write('4');
document.write('5');
setTimeout(function () {
document.write('8')
}, 1000)
};
setTimeout(function () {
document.write('6')
}, 0);
setTimeout(function () {
document.write('7')
}, 1000)
</script>
</body>
</html>
執行結果:頁面顯示67。
原因:document.write(‘6’) 在執行時,重寫了document,此時覆蓋掉了還沒有執行的onload 定義。
注意:如果document.write(‘6’)的延時小於100ms就會出現上面的結果,如果大於100ms的話(比如200ms),頁面最終顯示的就是45678
後續補充中…