// 维护已有的打点事件名称 防止命名重复
const eventNameList = [
'oh1Click'
]
class Duration {
constructor () {
this.eventMap = {}
}
// 打点设置开始时间
setStartTime (eventName) {
// 判断该事件名称是否注册
if (!eventNameList.includes(eventName)) {
throw new Error(`${eventName} 名称不存在 请在eventNameList文件中添加`)
}
// 判断该事件名称是否存在 存在 threw error
if (eventNameList.indexOf(eventName) !== eventNameList.lastIndexOf(eventName)) {
throw new Error(`${eventName} 名称已经存在 请更改名称`)
}
this.eventMap[eventName] = {}
this.eventMap[eventName].startTime = new Date().getTime()
}
// 计算 Duration
getDuration (eventName) {
const startTime = (this.eventMap[eventName] || {}).startTime
if (startTime) {
const duration = new Date().getTime() - startTime
const log = {
eventName,
duration
}
// 上报
console.log(log)
} else {
throw new Error(`${eventName} 未设置开始打点时间`)
}
}
start (eventName) {
if (Array.isArray(eventName)) {
eventName.forEach((item) => {
this.setStartTime(item)
})
} else {
this.setStartTime(eventName)
}
}
end (eventName) {
if (Array.isArray(eventName)) {
eventName.forEach((item) => {
this.getDuration(item)
})
} else {
this.getDuration(eventName)
}
}
}
const duration = new Duration
使用
// 单个动作打点
// 开始计时
duration.start('loading-start')
// 计时结束
duration.end('hh')
// 多个动作同步-联合打点
// 开始
duration.start(['oh1Click', 'hh'])
// 结束
duration.end(['hh','oh1Click'])