首页 > 解决方案 > Chrome - alert() 的 Javascript 执行顺序问题

问题描述

今天我想知道 Chrome 中 JavaScript 函数“alert()”的执行顺序

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">
test1 test1 test1 test1 
</div>

<div id="test2">
test2 test2 test2 test2 
</div>

<input type="button" onclick="runTest()" value="start test">

<script>

function runTest()
{
  $('#test1').css('background-color', 'red');
  alert('test1');

  $('#test2').css('background-color', 'red');
	alert('test2');
}

</script>

在 Firefox 62 和 IE11 中(按预期工作):

1) BGcolor Line 1  
2) Alertbox 1  
3) (click OK)  
4) BGcolor Line 2  
5) Alertbox 2  
6) (click OK) 

在 Chrome 69.0.3497.100 中:

1) Alertbox 1  
2) (click OK)   
3) Alertbox 2
4) (click OK)  
5) BGcolor Line 1  
6) BGcolor Line 2  

为什么 Chrome 不启动 alert() 并等待点击 OK?


谢谢奥利_

标签: javascriptgoogle-chrome

解决方案


通过对类似问题进行一些研究,这个问题的答案似乎是正确的:

...样式对象的更改会向页面渲染器触发重绘请求消息,并且在浏览器空闲时立即处理,即在此脚本例程结束之后。

显然,只有 Chrome 会这样做。


推荐阅读