0.0.5 • Published 8 years ago

task-throttler v0.0.5

Weekly downloads
18
License
MIT
Repository
github
Last release
8 years ago

task-throttler

This package can be used to throttle the execution of work. It is simple to use and uses async to perform the work asynchronously.

Quick Example Tests

it('performs tasks when limit or duration hit', function (done) {
    var throttler = new Throttler(10, 'series', 50);
    var arr = [];

    var i = 15;
    var callbackCount = 0;
    while (i--) {
        throttler.addTask(function (callback) {
            arr.push(throttler.tasks.length);
            callback();
        }, function () {
            callbackCount++;

            // Although we're adding tasks, they are not running until we hit our limit or delay.
            if (arr.length < 10) {
                arr.length.should.equal(0);
            }
            if (arr.length >= 10 && arr.length < 15) {
                arr.length.should.equal(10);
            }

            // Once we have iterated 15 times, final processing is triggered after the delay (50ms) or by calling process().
            if (arr.length === 15) {
                arr[0].should.equal(10);
                arr[9].should.equal(10);
                arr[14].should.equal(5);
                callbackCount.should.equal(16);

                console.log(arr);
                done();
            }
        });
    }
    throttler.process(); // don't wait for the delay, process right away.
});

it('example usage also throttling task adding', function (done) {
    var throttler = new Throttler(10, 'series', 50);
    var arr = [];
    var callbackCount = 0;

    iterate(15);

    function iterate(count) {
        throttler.addTask(function (callback) {
            arr.push(throttler.tasks.length);
            callback();
        }, function () {
            callbackCount++;

            // Although we're adding tasks, they are not running until we hit our limit or delay.
            if (arr.length < 10) {
                arr.length.should.equal(0);
            }
            if (arr.length >= 10 && arr.length < 15) {
                arr.length.should.equal(10);
            }

            // Once we have iterated 15 times, final processing is triggered after the delay (50ms) or by calling process().
            if (arr.length === 15) {
                arr[0].should.equal(10);
                arr[9].should.equal(10);
                arr[14].should.equal(5);
                callbackCount.should.equal(16);

                console.log(arr);
                done();
            }

            if (count > 1) setTimeout(function () {iterate(count - 1); }, 1);
        });
    }

});
0.0.5

8 years ago

0.0.4

9 years ago

0.0.3

9 years ago

0.0.2

9 years ago

0.0.1

9 years ago