html - JavaScript behaviour with blocking code -


function simulatecomplexoperation(sleepduration) {    var = new date().gettime();    while (new date().gettime() < + sleepduration) { /* nothing */ }  }    function testfunction() {    document.getelementbyid('panel1').style.display = 'none';    console.log('before');    simulatecomplexoperation(2000);    console.log('after');  }
<div id='panel1'>    text hidden  </div>    <button onclick="testfunction()">hide</button>

(jsfiddle)

this timeline:

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

why not:

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

is there way force style change operation first?

you preferably use settimeout. it's caused scheduling of code browser.

function simulatecomplexoperation(sleepduration) {    var = new date().gettime();    while (new date().gettime() < + sleepduration) { /* nothing */ }  }    function testfunction() {    document.getelementbyid('panel1').style.display = 'none';    console.log('before');    settimeout(() => {      console.log('after');    }, 2000);  }
<div id='panel1'>    text hidden  </div>    <button onclick="testfunction()">hide</button>


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -