2016-06-17 2 views
2

파일 크기 및 속도와 같은 다운로드 정보를 표시하는 다음 기능이 있습니다. 이 정보는 몇 초에 한 번 업데이트됩니다. 표시된 정보가 흔들리는 것을 막기 위해 매 2 초마다 progressInfo 섹션을 업데이트하고 싶습니다.스로틀 기능 2 초

이미 타임 아웃과 간격을 사용해 보았지만 작동하지 않는 것 같습니다.

https.get(options, function (update) { 
    update.on('data', function (chunk) { 
     file.write(chunk); 
     len += chunk.length; 
     fileDownloaded = (len/1048576).toFixed(1); 
     now = Date.now(); speed = len/(now - startTime)/1024; 
     speed = ' - ' + speed.toFixed(1) + ' MB/s'; 

     setInterval(function() { 
      progressInfo.html(fileDownloaded + ' MB of ' + speed); 
     }, 2000); 
    }); 
}); 

답변

0

의 간단한도 구현입니다 이미 호출되었습니다. 간단한 플래그를 사용하여 html을 업데이트해야하는지 아니면 processInfo 업데이트가 이미 시작되었는지 확인할 수 있습니다.

그리고 setIntervall(function, milliseconds) 대신 setTimeout(function, milliseconds)을 사용하면 processInfo 함수의 업데이트 만 실행됩니다.

var update = null; 
https.get(options, function (update) { 
    update.on('data', function (chunk) { 
     file.write(chunk); 
     len += chunk.length; 
     fileDownloaded = (len/1048576).toFixed(1); 
     now = Date.now(); speed = len/(now - startTime)/1024; 
     speed = ' - ' + speed.toFixed(1) + ' MB/s'; 
     If(update == null) { 
      update = false 
      updateHTML(); 
     } 
     else if(update) { 
      update = false; 
      setTimeout(updateHTML, 2000); 
     } 
    }); 
}); 

var updateHTML = function() { 
        progressInfo.html(fileDownloaded + ' MB of ' + speed); 
       update = true; 
} 
+0

이것은 처음에는 html을 업데이트하기 전에 2 초를 기다렸습니다. 이것은 html을 즉시 업데이트하고 2 초 지연을 부과 할 수 있도록 어떻게 변경 될 수 있습니까? –

+0

@ User394839859 이제 초기 업데이트가 즉시 완료됩니다. –

2

로다시 또는 밑줄의 스로틀 기능을 사용해보십시오. 밑줄 문서에서

:

_.throttle(function, wait, [options]) 

가 만들고 새로운를 반환

스로틀은 반복적으로 호출 할 때 만 실제로 호출 것, 전달 기능의 버전, 을 스로틀 원래 은 최대 대기 밀리 초마다 한 번만 작동합니다. 따라 잡을 수있는 것보다 빠르게 발생하는 속도 제한 이벤트 에 유용합니다.

function updateProgress(fileDownloaded, speed) { 
    progressInfo.html(fileDownloaded + ' MB of ' + speed); 
} 

function throttledProgress = _.throttle(updateProgress, 2000); 

https.get(options, function (update) { 
    update.on('data', function (chunk) { 
     file.write(chunk); 
     len += chunk.length; 
     fileDownloaded = (len/1048576).toFixed(1); 
     now = Date.now(); speed = len/(now - startTime)/1024; 
     speed = ' - ' + speed.toFixed(1) + ' MB/s'; 
     // invoked the throttled function here 
     throttledProgress(fileDownloaded, speed) 
    }); 
}); 

여기이 하나의 사건을 처리하기 위해 전체 외부 라이브러리를 추가하지 않으려면

그냥 함수 후 반복 함수 호출을 방지 스로틀 기능

var throttle = function(func, wait) { 
    var timer; 
    return function(){ 
    var currTime = new Date(); 
    var elapsed = currTime - timer; 
    if (timer === undefined || elapsed > wait){ 
     func.apply(this, arguments); 
     timer = currTime; 
    } 
    }; 
}; 
+0

그런 간단한 사례를 처리하기 위해 전체 외부 라이브러리를 추가하는 것이 좋은 방법인지 잘 모르겠습니다. –

+0

그것은 단지 옵션 일 뿐이며 공통 라이브러리 일 수 있습니다. 이미 응용 프로그램에서 사용 중이거나 다른 곳에서 다른 용도로 사용하고있을 수도 있습니다. 어느 쪽이든 나는 throttling 기능의 간단한 throttling 구현으로 대답을 업데이트했습니다. – jmancherje