微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

阻止代码的JavaScript行为

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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐