Skip to content
Snippets Groups Projects
Select Git revision
  • 374815f097c8b968a5e2a82ab1b94970c05cd7cb
  • master default protected
  • 1.31
  • 4.38.6
  • 4.38.5
  • 4.38.4
  • 4.38.3
  • 4.38.2
  • 4.38.1
  • 4.38.0
  • 4.37.2
  • 4.37.1
  • 4.37.0
  • 4.36.0
  • 4.35.0
  • 4.34.1
  • 4.34.0
  • 4.33.1
  • 4.33.0
  • 4.32.2
  • 4.32.1
  • 4.32.0
  • 4.31.0
23 results

deadmansswitch.mjs

Blame
  • Volker Schukai's avatar
    Volker Schukai authored
    374815f0
    History
    deadmansswitch.mjs 2.02 KiB
    /**
     * Copyright schukai GmbH and contributors 2023. All Rights Reserved.
     * Node module: @schukai/monster
     * This file is licensed under the AGPLv3 License.
     * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html
     */
    
    import { internalSymbol } from "../constants.mjs";
    
    import { Base } from "../types/base.mjs";
    import { isInteger } from "../types/is.mjs";
    import { validateFunction, validateInteger } from "../types/validate.mjs";
    
    export { DeadMansSwitch };
    
    /**
     * The dead man's switch allows to set a timer which can be reset again and again within a defined period of time.
     *
     * @externalExample ../../example/util/deadmansswitch.mjs
     * @copyright schukai GmbH
     * @license AGPLv3
     * @since 1.29.0
     * @memberOf Monster.Util
     * @summary Class to be able to execute function chains
     */
    class DeadMansSwitch extends Base {
    	/**
    	 * Create new dead man's switch
    	 *
    	 * @param {Integer} delay
    	 * @param {function} callback
    	 * @throw {TypeError} the arguments must be either integer or functions
    	 * @throws {TypeError} value is not an integer
    	 */
    	constructor(delay, callback) {
    		super();
    
    		init.call(this, validateInteger(delay), validateFunction(callback));
    	}
    
    	/**
    	 *
    	 * @param {Integer|undefined} [delay]
    	 */
    	touch(delay) {
    		if (this[internalSymbol]["isAlreadyRun"] === true) {
    			throw new Error("has already run");
    		}
    
    		if (isInteger(delay)) {
    			this[internalSymbol]["delay"] = delay;
    		} else if (delay !== undefined) {
    			throw new Error("unsupported argument");
    		}
    
    		clearTimeout(this[internalSymbol]["timer"]);
    
    		initCallback.call(this);
    
    		return this;
    	}
    }
    
    /**
     * @private
     */
    function initCallback() {
    
    	this[internalSymbol]["timer"] = setTimeout(() => {
    		this[internalSymbol]["isAlreadyRun"] = true;
    		this[internalSymbol]["callback"]();
    	}, this[internalSymbol]["delay"]);
    }
    
    /**
     * @private
     * @param {integer} delay
     * @param {function} callback
     */
    function init(delay, callback) {
    
    	this[internalSymbol] = {
    		callback,
    		delay,
    		isAlreadyRun: false,
    		timer: undefined,
    	};
    
    	initCallback.call(this);
    }