Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //WHY?
- //Restart guarding. (start/stop spamming)
- //Automated timeout/interval killing when flushed
- //Estimated time until flush of item you push on (assuming no stopping)
- (function() {
- //implements a spread out time queue for callbacks to be performed
- function LimitingQueue(ops_per_second) {
- this.items = []
- this.op_timer = 1000 / ops_per_second
- //restart bug guard requires knowledge of last cb being fired
- this.last_op = 0
- this.interval = false
- this.timeout = false
- }
- //Exporting for commonjs/node/browser
- if(module.exports) {
- exports.LimitingQueue = LimitingQueue.LimitingQueue = module.exports = LimitingQueue
- }
- else if(exports) {
- exports.LimitingQueue = LimitingQueue
- }
- else if(window) {
- window.LimitingQueue = LimitingQueue
- }
- //returns undefined if not appended
- //returns time at minimum until queue flushes to cb otherwise
- //check the return value with "r === undefined"
- LimitingQueue.prototype.push = function(cb,nostart) {
- if(typeof cb === "function") {
- this.items.push(cb)
- if(!nostart) {
- this.start()
- }
- //a general estimate, good enough for small timers
- return this.items.length * this.op_timer
- //an exact measurement for very large timers
- //var time_til = this.last_op - (+new Date()) + this.items.length * this.op_timer
- //return time_tile < 0 ? 0 : time_til
- }
- }
- //flush the first item on the queue
- //do not use
- LimitingQueue.prototype.flush = function() {
- if(this.items.length) {
- this.last_op = +new Date()
- this.items.shift()()
- }
- else {
- this.stop()
- }
- }
- //stops the queue where it is at
- LimitingQueue.prototype.stop = function() {
- //console.log("stopping")
- if(this.interval) {
- clearInterval(this.interval)
- this.interval = false
- clearTimeout(this.timeout)
- this.timeout = false
- }
- }
- //starts the queue back up
- LimitingQueue.prototype.start = function() {
- var self = this
- //dont want to wait on first one
- //self.flush()
- if(!this.interval) {
- function flush() {
- if(self.interval
- && self.last_op - (+new Date()) < 0) {
- self.flush()
- }
- }
- //first one shouldnt wait
- this.timeout = setTimeout(flush,0)
- this.interval = setInterval(flush,this.op_timer)
- }
- }
- })()
Add Comment
Please, Sign In to add comment