global.js 1.3 KB

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