Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mamayaya1
GitHub Repository: mamayaya1/game
Path: blob/main/projects/HexGL/bkcore.coffee/Timer.coffee
4626 views
1
###
2
new Date().getTime() wrapper to use as timer.
3
4
@class bkcore.Timer
5
@author Thibaut 'BKcore' Despoulain <http://bkcore.com>
6
###
7
class Timer
8
9
###
10
Creates a new timer, inactive by default.
11
Call Timer.start() to activate.
12
###
13
constructor: ()->
14
15
@time =
16
start: 0
17
current: 0
18
previous: 0
19
elapsed: 0
20
delta: 0
21
22
@active = false
23
24
###
25
Starts/restarts the timer.
26
###
27
start: ()->
28
29
now = (new Date).getTime()
30
31
@time.start = now
32
@time.current = now
33
@time.previous = now
34
@time.elapsed = 0
35
@time.delta = 0
36
37
@active = true
38
39
###
40
Pauses(true)/Unpauses(false) the timer.
41
42
@param bool Do pause
43
###
44
pause: (doPause)->
45
46
@active = not doPause
47
48
###
49
Update method to be called inside a RAF loop
50
###
51
update: ()->
52
53
if not @active then return
54
55
now = (new Date).getTime()
56
57
@time.current = now
58
@time.elapsed = @time.current - @time.start
59
@time.delta = now - @time.previous
60
@time.previous = now
61
62
###
63
Returns a formatted version of the current elapsed time using msToTime().
64
###
65
getElapsedTime: ()->
66
67
return @constructor.msToTime(@time.elapsed)
68
69
###
70
Formats a millisecond integer into a h/m/s/ms object
71
72
@param x int In milliseconds
73
@return Object{h,m,s,ms}
74
###
75
@msToTime: (t)->
76
77
ms = t%1000
78
s = Math.floor((t/1000)%60)
79
m = Math.floor((t/60000)%60)
80
h = Math.floor(t/3600000)
81
82
return {h:h, m:m, s:s, ms,ms}
83
84
###
85
Formats a millisecond integer into a h/m/s/ms object with prefix zeros
86
87
@param x int In milliseconds
88
@return Object<string>{h,m,s,ms}
89
###
90
@msToTimeString: (t)->
91
92
time = @msToTime(t)
93
94
time.h = @zfill(time.h, 2)
95
time.m = @zfill(time.m, 2)
96
time.s = @zfill(time.s, 2)
97
time.ms = @zfill(time.ms, 4)
98
99
return time
100
101
###
102
Convert given integer to string and fill with heading zeros
103
104
@param num int Number to convert/fill
105
@param size int Desired string size
106
###
107
@zfill: (num, size)->
108
109
len = size - num.toString().length
110
return if len > 0 then new Array(len+1).join('0') + num else num.toString()
111
112
###
113
Exports
114
@package bkcore
115
###
116
exports = exports ? @
117
exports.bkcore ||= {}
118
exports.bkcore.Timer = Timer
119