JavaScript阻塞代码的行为

4

function simulateComplexOperation(sleepDuration) {
  var now = new Date().getTime();
  while (new Date().getTime() < now + sleepDuration) { /* do nothing */ }
}

function testFunction() {
  document.getElementById('panel1').style.display = 'none';
  console.log('before');
  simulateComplexOperation(2000);
  console.log('after');
}
<div id='panel1'>
  text to hidden
</div>

<button onclick="testFunction()">Hide</button>

(jsFiddle)

以下是时间轴:

  • 打印“before”
  • 等待2秒
  • 打印“after”
  • 隐藏ID为'panel1'的元素

为什么不是这样的:

  • 隐藏ID为'panel1'的元素
  • 打印“before”
  • 等待2秒
  • 打印“after”

有没有办法强制使样式更改操作成为第一个?


3
由于浏览器如何安排渲染的原因。 - Jaromanda X
2
使用WebWorkers来进行后台工作。 - Phylogenesis
请看这个答案:https://dev59.com/Upbfa4cB1Zd3GeqPzdZF#37092024 - Mekicha
1个回答

0
你最好使用setTimeout。但这是由浏览器对代码的调度引起的。

function simulateComplexOperation(sleepDuration) {
  var now = new Date().getTime();
  while (new Date().getTime() < now + sleepDuration) { /* do nothing */ }
}

function testFunction() {
  document.getElementById('panel1').style.display = 'none';
  console.log('before');
  setTimeout(() => {
    console.log('after');
  }, 2000);
}
<div id='panel1'>
  text to hidden
</div>

<button onclick="testFunction()">Hide</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接