为什么 window.scrollTo() 需要 setTimeout() 才能工作?

Lab*_*dor 5 javascript scroll dom-events

这是一个 HTML 页面,在左上角显示三个方形 div:

window.addEventListener('load', function () {
  console.log('load event has fired')
  window.scrollTo(500, 0);
  // setTimeout(function() { window.scrollTo(500, 0); }, 0);
})
Run Code Online (Sandbox Code Playgroud)
body { height: 100vh }
.bigwidth {
  width: 2000px;
  display: block;
}
.square {
  width: 100px;
  height: 100px;
  display: block;
  position: absolute;
}
.greenish {
  background-color: #75af99;
}
.redish {
  background-color: #ff9b98;
}
.bluish {
  background-color: #aabbff;
}
.whiteish {
  background-color: #eaeaea;
}
* {
  padding: 0;
  margin: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div class="whiteish bigwidth" style="height:100%;">
    <div class="square greenish" style="left:50px; top:50px;"></div>
    <div class="square redish" style="left:70px; top:70px;"></div>
    <div class="square bluish" style="left:90px; top:90px;"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

现在,window.scrollTo(500, 0);页面加载时发生的命令没有效果(在 safari 和 Chrome 中测试)。但如果我们用行替换它

setTimeout(function() { window.scrollTo(500, 0); }, 0);
Run Code Online (Sandbox Code Playgroud)

(在上面的代码中注释掉),滚动确实发生了。为什么是这样?