forked from nuxt/nuxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.js
More file actions
65 lines (59 loc) · 1.46 KB
/
timer.js
File metadata and controls
65 lines (59 loc) · 1.46 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
61
62
63
64
65
async function promiseFinally (fn, finalFn) {
let result
try {
if (typeof fn === 'function') {
result = await fn()
} else {
result = await fn
}
} finally {
finalFn()
}
return result
}
export const timeout = function timeout (fn, ms, msg) {
let timerId
const warpPromise = promiseFinally(fn, () => clearTimeout(timerId))
const timerPromise = new Promise((resolve, reject) => {
timerId = setTimeout(() => reject(new Error(msg)), ms)
})
return Promise.race([warpPromise, timerPromise])
}
export const waitFor = function waitFor (ms) {
return new Promise(resolve => setTimeout(resolve, ms || 0))
}
export class Timer {
constructor () {
this._times = new Map()
}
start (name, description) {
const time = {
name,
description,
start: this.hrtime()
}
this._times.set(name, time)
return time
}
end (name) {
if (this._times.has(name)) {
const time = this._times.get(name)
time.duration = this.hrtime(time.start)
this._times.delete(name)
return time
}
}
hrtime (start) {
const useBigInt = typeof process.hrtime.bigint === 'function'
if (start) {
const end = useBigInt ? process.hrtime.bigint() : process.hrtime(start)
return useBigInt
? (end - start) / BigInt(1000000)
: (end[0] * 1e3) + (end[1] * 1e-6)
}
return useBigInt ? process.hrtime.bigint() : process.hrtime()
}
clear () {
this._times.clear()
}
}