2017-08-18 36 views
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)的JavaScript行为

这是时间轴:

  • 打印 “之前”
  • 等待2秒
  • 打印“之后“
  • 隐藏元素ID为 'PANEL1'

为什么不:id为 'PANEL1'

  • 打印

    • 隐藏元素 “前”
    • 间隔2秒
    • 打印“after”

    有没有办法强制风格ch愤怒操作成为第一个?

  • +3

    因为浏览器如何安排渲染 –

    +2

    使用[WebWorkers(https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)至做后台工作。 – Phylogenesis

    +0

    看看这个答案:https://stackoverflow.com/a/37092024/3865670 – Mekicha

    回答

    0

    你最好使用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>