我有以下函数来显示下载信息,例如文件大小和速度。这些信息似乎每秒更新几次。我只想每 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);
});
});
最佳答案
尝试使用 lodash 或 underscore 的节流函数。
来自下划线文档:
throttle
_.throttle(function, wait, [options])
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.
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;
}
};
};
关于javascript - throttle 功能2秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37873275/