cbp-lib
Version:
Libraries for cbp
56 lines (44 loc) • 1.4 kB
JavaScript
'use strict'
import {Log} from "../_helpers/Log"
const DefaultTimer = 5
let _ = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {};
export class Timer {
constructor(callback, name) {
this._name = name
this._callback = callback
}
get now() {
return parseInt(Date.now() / 1000)
}
init(duration) {
Log.debug("Timer.init: Timer initialized...")
if (duration <= 0) {
duration = 1
}
duration = parseInt(duration)
var expiration = this.now + duration
if (this._expiration === expiration && this._timer) {
Log.debug("Timer.js: is initialized")
return;
}
this.cancel();
this._expiration = expiration
Log.debug("Timer: Setting setInterval.." + this._expiration)
this._timer = _.setInterval(this.callback.bind(this), DefaultTimer * 1000);
}
cancel() {
if (this._timer) {
Log.debug("Timer.js: stopping timer...")
_.clearInterval(this._timer)
this._timer = null
}
}
callback() {
var diff = this._expiration - this.now;
Log.debug("Timer.callback; " + this._name + " timer expires in: " + diff);
if (this._expiration <= this.now) {
this.cancel()
this._callback(1)
}
}
}