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/