-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtimer.js
69 lines (54 loc) · 1.24 KB
/
timer.js
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
61
62
63
64
65
66
67
68
69
/*
* Copyright (c) 2016-present, IBM Research
* Licensed under The MIT License [see LICENSE for details]
*/
"use strict";
const SECOND_MS = 1000;
const MINUTE_MS = 60 * SECOND_MS;
const HOUR_MS = 60 * MINUTE_MS;
function Timer(logger, method = "log")
{
this.currentTime = new Date();
this.logger = logger || console;
this.method = method || "log";
}
Timer.prototype.getCurrentTime = function()
{
let past = parseFloat(this.currentTime.getTime());
let now = new Date().getTime();
now = parseFloat(now);
return (now - past) / SECOND_MS;
}
Timer.prototype.getTimeString = function()
{
let past = parseFloat(this.currentTime.getTime());
let now = new Date().getTime();
now = parseFloat(now);
let deltaT = now - past;
if(deltaT > HOUR_MS)
{
return (deltaT / HOUR_MS).toFixed(2) + "hrs";
}
else if(deltaT > MINUTE_MS)
{
return (deltaT / MINUTE_MS).toFixed(2) + "min";
}
else if(deltaT > SECOND_MS)
{
return (deltaT / SECOND_MS).toFixed(2) + "s";
}
else
{
return deltaT + "ms";
}
}
Timer.prototype.restart = function()
{
this.currentTime = new Date();
}
Timer.prototype.tick = function(...args)
{
this.logger[this.method].apply(this.logger, args.concat([this.getTimeString()]));
this.restart();
}
module.exports = Timer;