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)

This is the timeline:

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

Why is it not:

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

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

chazsolo
  • 7,873
  • 1
  • 20
  • 44

1 Answers1

0

You would preferably use setTimeout. But it's caused by the scheduling of the code by the browser.

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>
sascha10000
  • 1,245
  • 1
  • 10
  • 22