function freezeProp(obj, prop) { Object.defineProperty(obj, prop, {configurable: false, writable: false}); } function guidGenerator() { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); } class Thread { constructor() { this.id = guidGenerator(); freezeProp(this, "id"); this.stopped = false; this.running = false; this.runOnce = null; this.runConstantly = null; this.context = {}; } set(runOnce, runConstantly) { this.runOnce = () => runOnce.apply(this.context); this.runConstantly = () => runConstantly.apply(this.context); } start() { if (!this.running) { const self = this.context; const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); self.delay = delay; self.id = this.id; self.dis = {}; freezeProp(self, "id"); freezeProp(self, "delay"); const runConstantlyFunc = async () => { while (!this.stopped) { await this.runConstantly.apply(this.context); for (var member in self.dis) delete self.dis[member]; } }; if (this.runOnce != null) { (async () => { await this.runOnce.apply(this.context); if (this.runConstantly != null) { runConstantlyFunc(); } })(); } else if (this.runConstantly != null) { runConstantlyFunc(); } } else { this.stopped = false; } } stop() { this.stopped = true; } }