UNPKG

homebridge-smartsystem

Version:

SmartServer (Proxy Websockets to TCP sockets, Smappee MQTT, Duotecno IP Nodes, Homekit interface)

56 lines (46 loc) 1.33 kB
import { debug, LogLevel, logSettings } from "./logger"; export class Q { private timer = null; private queue = []; constructor() { logSettings["Q"] = LogLevel.log; } exec(fn) { const len = this.queue.length; this.queue.push(fn); // start timer to execute this functon if nobody else calls "do" // this.logger("exec, we've put stuff in the queue, start " + (len ? "long timer" : "short timer")); this.startWaiter(len ? 500 : 0); } endWaiter() { if (this.timer) { debug("Q", "Waiter: clearing timer"); clearTimeout(this.timer); } } startWaiter(mSecs = 1000) { this.endWaiter(); debug("Q", "Waiter: starting timer for " + mSecs + " mSec"); this.timer = setTimeout(() => { debug("Q", "Waiter: timer finished, calling 'do' because nobody else did"); this.do(); }, mSecs); } do() { debug("Q", "Do, qlen="+ this.queue.length); // Get the oldest function and execute if (this.queue.length > 0) { const fn = this.queue[0]; this.queue.splice(0, 1); debug("Q", "Do: calling function"); fn(); } // Still stuff to execute if (this.queue.length > 0) { debug("Q", "Do, still stuff in the queue, start timer"); this.startWaiter(); } else { this.endWaiter(); } } }