JavaScript Behavior with Blocking Code

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>
Run codeHide result

( jsFiddle )

This is the timeline:

  • Prints "before"
  • wait 2 seconds
  • Prints after
  • hide element with id 'panel1'

Why is this not so:

  • hide element with id 'panel1'
  • Prints "before"
  • wait 2 seconds
  • Prints after

Is there a way to get the style change operation to be first?

+4
source share
1 answer

It is preferable to use setTimeout. But this is due to browser code scheduling.

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>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1683954/


All Articles