javascript - throttle 功能2秒

标签 javascript node.js

我有以下函数来显示下载信息,例如文件大小和速度。这些信息似乎每秒更新几次。我只想每 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/

相关文章:

javascript - 使用 session 存储变量

node.js - 我可以使用服务器端生成的 token 将文件上传到客户端的谷歌驱动器(angularjs)

javascript - node/lib 中的 *.js 文件是否在 Node 可执行文件的编译过程中使用?

javascript - 通过 gm 流式传输使用 Express.js 上传的文件以消除双写

javascript - 如何仅在满足条件时更新文档?

javascript - 当选择器进入 iFrame 时如何使用 $(window).delegate ('selector' ,'resize' ,函数处理程序)?

javascript - d3.js:访问向下嵌套 2 级的数据

javascript - HTML Doc 加载 JS 或 CSS 时,如何使用 PHP 减少 http 请求?

javascript - 在 NodeJS 服务器上本地使用 TypeKit

javascript - 在javascript中检查数组中的所有值是否相同