Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. 'use strict';
  2. class AbortError extends Error {
  3. constructor() {
  4. super('Throttled function aborted');
  5. this.name = 'AbortError';
  6. }
  7. }
  8. const pThrottle = ({limit, interval, strict}) => {
  9. if (!Number.isFinite(limit)) {
  10. throw new TypeError('Expected `limit` to be a finite number');
  11. }
  12. if (!Number.isFinite(interval)) {
  13. throw new TypeError('Expected `interval` to be a finite number');
  14. }
  15. const queue = new Map();
  16. let currentTick = 0;
  17. let activeCount = 0;
  18. function windowedDelay() {
  19. const now = Date.now();
  20. if ((now - currentTick) > interval) {
  21. activeCount = 1;
  22. currentTick = now;
  23. return 0;
  24. }
  25. if (activeCount < limit) {
  26. activeCount++;
  27. } else {
  28. currentTick += interval;
  29. activeCount = 1;
  30. }
  31. return currentTick - now;
  32. }
  33. const strictTicks = [];
  34. function strictDelay() {
  35. const now = Date.now();
  36. if (strictTicks.length < limit) {
  37. strictTicks.push(now);
  38. return 0;
  39. }
  40. const earliestTime = strictTicks.shift() + interval;
  41. if (now >= earliestTime) {
  42. strictTicks.push(now);
  43. return 0;
  44. }
  45. strictTicks.push(earliestTime);
  46. return earliestTime - now;
  47. }
  48. const getDelay = strict ? strictDelay : windowedDelay;
  49. return function_ => {
  50. const throttled = function (...args) {
  51. if (!throttled.isEnabled) {
  52. return (async () => function_.apply(this, args))();
  53. }
  54. let timeout;
  55. return new Promise((resolve, reject) => {
  56. const execute = () => {
  57. resolve(function_.apply(this, args));
  58. queue.delete(timeout);
  59. };
  60. timeout = setTimeout(execute, getDelay());
  61. queue.set(timeout, reject);
  62. });
  63. };
  64. throttled.abort = () => {
  65. for (const timeout of queue.keys()) {
  66. clearTimeout(timeout);
  67. queue.get(timeout)(new AbortError());
  68. }
  69. queue.clear();
  70. strictTicks.splice(0, strictTicks.length);
  71. };
  72. throttled.isEnabled = true;
  73. return throttled;
  74. };
  75. };
  76. module.exports = pThrottle;
  77. module.exports.AbortError = AbortError;