Guest User

Untitled

a guest
Jun 18th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. //WHY?
  2. //Restart guarding. (start/stop spamming)
  3. //Automated timeout/interval killing when flushed
  4. //Estimated time until flush of item you push on (assuming no stopping)
  5. (function() {
  6. //implements a spread out time queue for callbacks to be performed
  7. function LimitingQueue(ops_per_second) {
  8. this.items = []
  9. this.op_timer = 1000 / ops_per_second
  10. //restart bug guard requires knowledge of last cb being fired
  11. this.last_op = 0
  12. this.interval = false
  13. this.timeout = false
  14. }
  15. //Exporting for commonjs/node/browser
  16. if(module.exports) {
  17. exports.LimitingQueue = LimitingQueue.LimitingQueue = module.exports = LimitingQueue
  18. }
  19. else if(exports) {
  20. exports.LimitingQueue = LimitingQueue
  21. }
  22. else if(window) {
  23. window.LimitingQueue = LimitingQueue
  24. }
  25.  
  26. //returns undefined if not appended
  27. //returns time at minimum until queue flushes to cb otherwise
  28. //check the return value with "r === undefined"
  29. LimitingQueue.prototype.push = function(cb,nostart) {
  30. if(typeof cb === "function") {
  31. this.items.push(cb)
  32. if(!nostart) {
  33. this.start()
  34. }
  35. //a general estimate, good enough for small timers
  36. return this.items.length * this.op_timer
  37. //an exact measurement for very large timers
  38. //var time_til = this.last_op - (+new Date()) + this.items.length * this.op_timer
  39. //return time_tile < 0 ? 0 : time_til
  40. }
  41. }
  42. //flush the first item on the queue
  43. //do not use
  44. LimitingQueue.prototype.flush = function() {
  45. if(this.items.length) {
  46. this.last_op = +new Date()
  47. this.items.shift()()
  48. }
  49. else {
  50. this.stop()
  51. }
  52. }
  53. //stops the queue where it is at
  54. LimitingQueue.prototype.stop = function() {
  55. //console.log("stopping")
  56. if(this.interval) {
  57. clearInterval(this.interval)
  58. this.interval = false
  59. clearTimeout(this.timeout)
  60. this.timeout = false
  61. }
  62. }
  63. //starts the queue back up
  64. LimitingQueue.prototype.start = function() {
  65. var self = this
  66. //dont want to wait on first one
  67. //self.flush()
  68. if(!this.interval) {
  69. function flush() {
  70. if(self.interval
  71. && self.last_op - (+new Date()) < 0) {
  72. self.flush()
  73. }
  74. }
  75. //first one shouldnt wait
  76. this.timeout = setTimeout(flush,0)
  77. this.interval = setInterval(flush,this.op_timer)
  78. }
  79. }
  80. })()
Add Comment
Please, Sign In to add comment