2016-06-17 11 views
2

ファイルサイズやスピードなどのダウンロード情報を表示する次の機能があります。情報は1秒に数回更新されるようです。表示された情報をジッタから守るために、progressInfoセクションを2秒ごとに更新するだけです。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関数の更新を1つだけ実行することができます。

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]) 

を作成し、新しいを返し、繰り返し呼び出されたときに、唯一実際に呼び出す、という 、渡された関数のバージョンを絞ります元の は、たいてい、待機時間ごとに1回のミリ秒で機能します。あなたが追いつくことができるよりも速く発生するレート制限イベント に役立ちます。

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) 
    }); 
}); 

あなたはこの1ケースを処理するために、全体の外部ライブラリを追加したくない場合は、ここでスロットリング機能の簡単なimplimentationだ

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

これは単なる選択肢であり、共通のライブラリである可能性があります。アプリケーションで既に使用されているか、他の用途に使用されている可能性があります。いずれの方法でも、調整機能の単純な調整で回答を更新しました。 – jmancherje

関連する問題