UNPKG

ioto-multi-tap

Version:

一个用于处理短时间内连续触发调用的 JavaScript 工具类

40 lines (39 loc) 2.02 kB
class r { /** * 构造函数 * * @param {Function[]} handlers - 一个函数数组,对应连续调用次数的处理函数: * handlers[0] 用于 1 次调用, * handlers[1] 用于 2 次调用, * handlers[2] 用于 3 次调用(可选),依次类推。 * 至少需要提供前两个处理函数。 * @param {number} [interval=400] - 多次调用之间允许的间隔(毫秒),默认为 400ms。 * * @throws {Error} 当 handlers 不是数组或数量少于 2 时抛出错误。 */ constructor(t, i = 400) { if (!Array.isArray(t) || t.length < 2) throw new Error("必须提供至少两个处理函数(handler)。"); this.handlers = t, this.interval = i, this.count = 0, this.timer = null; } /** * 触发调用记录。每次外部事件(例如按键)到来时,请调用此方法, * 系统会在间隔期内统计调用次数,超过间隔后执行对应的处理函数。 * * 执行逻辑: * 1. 每次调用 trigger() 时,将内部计数器加 1。 * 2. 如果之前已经启动了等待计时器则清除计时器,开始一个新的 400ms 倒计时。 * 3. 当 400ms 过去没有新的调用时,依据计数器值选择对应的处理函数执行: * - 如果 handlers 中存在与计数器相应的处理函数,则执行之; * - 否则,使用 handlers 数组中的最后一个处理函数作为默认(也适用于超过已设定的次数)。 * 4. 执行完成后,重置计数器和计时器。 */ trigger(t) { this.count++, this.timer && clearTimeout(this.timer), this.timer = setTimeout(() => { const i = this.count - 1; (this.handlers[i] || this.handlers[this.handlers.length - 1])(t, this.count), this.count = 0, this.timer = null; }, this.interval); } } module.exports = { MultiTap: r }; //# sourceMappingURL=multi-tap.mjs.map