global.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. class Timer {
  3. constructor(callback, delay, paused) {
  4. this.callback = callback;
  5. this.delay = delay;
  6. this.paused = paused;
  7. this.timerId = delay;
  8. this.start = delay;
  9. this.remaining = delay;
  10. this.timeWhenPaused = 0;
  11. this.timePaused = Date.now();
  12. }
  13. pause() {
  14. clearTimeout(this.timerId);
  15. this.remaining -= Date.now() - this.start;
  16. this.timePaused = Date.now();
  17. }
  18. ifNotPaused() {
  19. if (!this.paused) {
  20. this.resume();
  21. }
  22. }
  23. resume() {
  24. this.start = Date.now();
  25. clearTimeout(this.timerId);
  26. this.timerId = setTimeout(this.callback, this.remaining);
  27. this.timeWhenPaused = Date.now() - this.timePaused;
  28. }
  29. resetTimeWhenPaused() {
  30. this.timeWhenPaused = 0;
  31. }
  32. timeWhenPaused() {
  33. return this.timeWhenPaused;
  34. }
  35. }
  36. function getRandomNumber(min, max) {
  37. return Math.floor(Math.random() * (max - min + 1)) + min;
  38. }
  39. module.exports = {
  40. io: null, // Socket.io
  41. db: null, // Database
  42. htmlEntities: str => {
  43. return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  44. },
  45. getRandomNumber,
  46. generateRandomString: len => {
  47. let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
  48. let result = [];
  49. for (let i = 0; i < len; i++) {
  50. result.push(chars[getRandomNumber(0, chars.length - 1)]);
  51. }
  52. return result.join("");
  53. },
  54. Timer
  55. };