timer.js
1.4 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
66
67
68
69
70
71
/* eslint-disable no-return-assign */
/**
* 计时器
* 支持链式调用
* timeout()
* .then(()=>{
* return inTheEnd();
* })
* .then(()=>{
* return inTheEnd();
* });
*
* @date 2019-11-25
*/
class Timer {
/**
* 延时操作
* @returns {void}
* @date 2019-11-25
*/
timeout (interval, args) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(args)
}, interval)
})
}
/**
* 等待代码片段执行完毕后再执行
* @returns {void}
* @date 2019-11-25
*/
inTheEnd () {
return this.timeout(0)
}
/**
* 循环定时, 执行回调后再继续下一轮循环
* @param {Number} interval 执行间隔
* @param {Function} [callback] 回调
* @returns {Object}
* @date 2019-11-25
*/
interval (interval, callback) {
this.timeout(interval)
.then(() => {
typeof callback === 'function' &&
callback() !== false &&
this.interval(interval, callback)
})
return { then: c => callback = c }
}
/**
* 计时,单位毫秒
* @returns {void}
* @date 2019-11-29
*/
start () {
const startDate = new Date()
return {
stop () {
const stopDate = new Date()
return stopDate.getTime() - startDate.getTime()
}
}
}
}
export default new Timer()