Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. var stack = [],
  2. timer = null;
  3.  
  4. function process() {
  5. var item = stack.shift();
  6. // process
  7. if (stack.length === 0) {
  8. clearInterval(timer);
  9. timer = null;
  10. }
  11. }
  12.  
  13. function queue(item) {
  14. stack.push(item);
  15. if (timer === null) {
  16. timer = setInterval(process, 500);
  17. }
  18. }
  19.  
  20. function RateLimit(fn, delay, context) {
  21. var canInvoke = true,
  22. queue = [],
  23. timeout,
  24. limited = function () {
  25. queue.push({
  26. context: context || this,
  27. arguments: Array.prototype.slice.call(arguments)
  28. });
  29. if (canInvoke) {
  30. canInvoke = false;
  31. timeEnd();
  32. }
  33. };
  34. function run(context, args) {
  35. fn.apply(context, args);
  36. }
  37. function timeEnd() {
  38. var e;
  39. if (queue.length) {
  40. e = queue.splice(0, 1)[0];
  41. run(e.context, e.arguments);
  42. timeout = window.setTimeout(timeEnd, delay);
  43. } else
  44. canInvoke = true;
  45. }
  46. limited.reset = function () {
  47. window.clearTimeout(timeout);
  48. queue = [];
  49. canInvoke = true;
  50. };
  51. return limited;
  52. }
  53.  
  54. function foo(x) {
  55. console.log('hello world', x);
  56. }
  57. var bar = RateLimit(foo, 1e3);
  58. bar(1); // logs: hello world 1
  59. bar(2);
  60. bar(3);
  61. // undefined, bar is void
  62. // ..
  63. // logged: hello world 2
  64. // ..
  65. // logged: hello world 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement