UNPKG

trickle

Version:

Slows incoming stream data to specific intervals

44 lines (38 loc) 1.14 kB
var through = require('through'); module.exports = function TrickleStream(options) { var options = options || {} , queued = [] , finishing = false , interval = false , stream options.interval = options.interval || 50; options.flush = options.flush || 1; options.limit = options.limit || 0; options.mru = options.mru || false; interval = setInterval(function() { var next, i for (i = 0; i < options.flush; i += 1) { next = queued.splice(0, 1)[0]; if (!next) break; if (!i) stream.resume(); stream.emit('data', next); } if (finishing && !queued.length) { stream.emit('end'); clearInterval(interval); } }, options.interval); stream = through(function write(data) { this.pause(); if (!options.limit || queued.length < options.limit) { queued.push(data); } else if (options.mru) { queued.shift(); queued.push(data); } }, function end() { finishing = true; }); return stream; };