forked from DuendeArchive/identity-model-oidc-client-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimer.js
More file actions
60 lines (48 loc) · 1.73 KB
/
Timer.js
File metadata and controls
60 lines (48 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
import Log from './Log';
import Global from './Global';
import Event from './Event';
const TimerDuration = 5; // seconds
export default class Timer extends Event {
constructor(name, timer = Global.timer) {
super(name);
this._timer = timer;
this._nowFunc = () => Date.now() / 1000;
}
get now() {
return parseInt(this._nowFunc());
}
init(duration) {
this.cancel();
if (duration <= 0) {
duration = 1;
}
duration = parseInt(duration);
Log.debug("Timer.init timer " + this._name + " for duration:", duration);
this._expiration = this.now + duration;
// we're using a fairly short timer and then checking the expiration in the
// callback to handle scenarios where the browser device sleeps, and then
// the timers end up getting delayed.
var timerDuration = TimerDuration;
if (duration < timerDuration) {
timerDuration = duration;
}
this._timerHandle = this._timer.setInterval(this._callback.bind(this), timerDuration * 1000);
}
cancel() {
if (this._timerHandle) {
Log.debug("Timer.cancel: ", this._name);
this._timer.clearInterval(this._timerHandle);
this._timerHandle = 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();
super.raise();
}
}
}