2017-08-18 32 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>