2014-12-02 3 views
0

다음 호를 실행했습니다. 로드 진행률 표시 줄을 표시하고 함수가 실행 된 후에 사라지는 함수 주위에 래퍼를 작성했습니다. 이제 함수 foo 실행시 중단 점을 설정할 때를 제외하고는 진행률 막대가 표시되지 않습니다.디버깅 할 때 DOM 만 업데이트

progress onload 이벤트에서 실행하는 데 약간의 성공을 거뒀지만 endLoading은 실행되지 않습니다.

function sleep(milliseconds) { 
    var start = new Date().getTime(); 
    for (var i = 0; i < 1e7; i++) if ((new Date().getTime() - start) > milliseconds) break; 
} 

var progress = document.createElement('progress'); 
var fillElement = document.body; 

function foo() { 
    console.log('foo start'); 
    sleep(2000); 
    fillElement.innerHTML = 'Bar'; 
    console.log('foo end'); } 

function startLoading() { 
    console.log('start'); 
    fillElement.innerHTML = ''; 
    fillElement.appendChild(progress);  
} 

function endLoading() { 
    console.log('end'); 
    fillElement.removeChild(progress); 
} 

startLoading(); 
foo(); // if the debug point is set here i can see the progress bar 
endLoading(); 
+1

바쁜 루핑 대신 ['setTimeout'] (https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Timers)를 사용하십시오. –

+1

브라우저는 단일 스레드이며, 다른 일이 일어나기 전에 상황이 완료 될 때까지 실행됩니다. 즉, 자바 스크립트가 끝날 때까지 DOM 다시 그리기가 수행되지 않습니다. 중단 점이 있으면 스크립트가 일시 중지되고 브라우저는 DOM에서 자바 스크립트가 의도 한 내용의 현재 상태를 반영하기 위해 다시 칠하기 위해 시간을 사용합니다. –

+1

JavaScript로 수면을 할 수 없습니다. 나쁜 생각은 ... 그건 for 루프가 DOM을 업데이트하는 것을 허용하지 않습니다. – epascarello

답변

0
function foo() { 
    console.log('foo start'); 
    setTimeout(function() { 
    fillElement.innerHTML = 'Bar'; 
    console.log('foo end'); 
    }, 2000); 
} 

function foo() { 
    console.log('foo start'); 
    sleep(2000); 
    fillElement.innerHTML = 'Bar'; 
    console.log('foo end'); } 

의 동등해야하고 함께 체인 운영

startLoading(chain(foo, endLoading)); 

function chain(x, y) { 
    return function() { x(y); } 
} 

function foo(afterwards) { 
    console.log('foo start'); 
    setTimeout(
    function() { 
     fillElement.innerHTML = 'Bar'; 
     console.log('foo end'); 
     afterwards(); 
    }, 
    2000); 
} 

할 수 있고 할 유사한 계속 통과 startLoading에 변환. 이 코딩 스타일을 단순화 할 수있는 미래를 들여다 볼 수도 있습니다.