User394839859 User394839859 - 5 months ago 15
Node.js Question

Throttle function for 2 seconds

I have the following function that displays download information such as file size and speed. The information seems to get updated several times a second. I would like to only have the

progressInfo
section updated every 2 seconds to keep the displayed information from jittering.

I've already tried using timeouts and intervals, but can't seem to get this to work.

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

Answer

Just prevent the repeated function call after a function is already called. You can use a simple flag to check if the html should be updated or a processInfo update is already started.

And use setTimeout(function, milliseconds) instead of setIntervall(function, milliseconds) to execute the update of processInfo function only ones.

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