带有阻塞代码的 JavaScript 行为

标签 javascript html

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 )

这是时间线:

  • 打印“之前”
  • 等2秒
  • 打印“之后”
  • 隐藏id为'panel1'的元素

为什么不是:

  • 隐藏id为'panel1'的元素
  • 打印“之前”
  • 等2秒
  • 打印“之后”

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

最佳答案

您最好使用 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>

关于带有阻塞代码的 JavaScript 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45755883/

相关文章:

javascript - 类型错误 : Cannot read property 'width' of undefined at getFeaturedImage (related. js:24)

javascript - 无法读取 null 的属性 'getHostNode'

javascript - jQuery animate 在 IE 中的工作方式有所不同

Javascript:2 个用户输入值的平均值

javascript - 将 typescript 和 javascript 文件集成到同一个项目中

javascript - navigator.serviceWorker 当注册多个 service worker 时

javascript - 使用 getElelementsByClass 翻转多张卡片

c# - 如何使用字段 ID 从 SQL Server 数据库中获取字段名

php - 如何使用 textlink POST 方法提交表单

html - 始终居中图像