油门function2秒

我有以下function,显示下载信息,如文件大小和速度。 该信息似乎每秒更新几次。 我只想每2秒更新一次progressInfo部分,以防止抖动显示的信息。

我已经尝试使用超时和间隔,但似乎无法得到这个工作。

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

在一个函数已经被调用之后,防止重复的函数调用。 您可以使用简单的标志来检查是否应该更新html或者processInfo更新已经启动。

并使用setTimeout(function, milliseconds)代替setIntervall(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; } 

尝试使用lodash或下划线的油门function。

从下划线文档:

风门

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

创build并返回传递函数的一个新的节制版本,在重复调用时,每等待几毫秒只能实际调用原始函数一次。 对速度限制事件有用,速度限制事件发生得比你能跟得上的速度快。

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

如果你不想添加一个完整的外部库来处理这个情况,这里就是一个简单的节stream函数的实现

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