Facebook
From Salvatore, 1 Month ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 111
  1. function freezeProp(obj, prop) {
  2.   Object.defineProperty(obj, prop, {configurable: false, writable: false});
  3. }
  4.  
  5. function guidGenerator() {
  6.   var S4 = function() {
  7.     return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  8.   };
  9.   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
  10. }
  11.  
  12. class Thread {
  13.   constructor() {
  14.     this.id = guidGenerator();
  15.     freezeProp(this, "id");
  16.     this.stopped = false;
  17.     this.running = false;
  18.     this.runOnce = null;
  19.     this.runConstantly = null;
  20.     this.context = {};
  21.   }
  22.  
  23.   set(runOnce, runConstantly) {
  24.     this.runOnce = () => runOnce.apply(this.context);
  25.     this.runConstantly = () => runConstantly.apply(this.context);
  26.   }
  27.  
  28.   start() {
  29.     if (!this.running) {
  30.       const self = this.context;
  31.  
  32.       const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
  33.       self.delay = delay;
  34.       self.id = this.id;
  35.       self.dis = {};
  36.       freezeProp(self, "id");
  37.       freezeProp(self, "delay");
  38.  
  39.       const runConstantlyFunc = async () => {
  40.         while (!this.stopped) {
  41.           await this.runConstantly.apply(this.context);
  42.           for (var member in self.dis) delete self.dis[member];
  43.         }
  44.       };
  45.  
  46.       if (this.runOnce != null) {
  47.         (async () => {
  48.           await this.runOnce.apply(this.context);
  49.           if (this.runConstantly != null) {
  50.             runConstantlyFunc();
  51.           }
  52.         })();
  53.       } else if (this.runConstantly != null) {
  54.         runConstantlyFunc();
  55.       }
  56.     } else {
  57.       this.stopped = false;
  58.     }
  59.   }
  60.  
  61.   stop() {
  62.     this.stopped = true;
  63.   }
  64. }