• timer.js 介绍
  • psrheartache
  • #timer.js
  • 2020-03-19
  • Wuhan,China
  • 197
  • 1 min read

# timer.js 介绍

Timer.js 是一个简单而轻量的定时器管理库,并且无依赖。

# 安装

npm install timer.js
1

# 使用示例

制作披萨的倒计时

import Timer from 'timer.js'
var pizzaTimer = new Timer();
var pizzaCookingTime = 15 * 60; // 15 minutes

pizzaTimer.start(pizzaCookingTime).on('end', function () {
  alert('Pizza is ready, bon appetit!');
});
1
2
3
4
5
6
7

所有的方法都支持链式操作

myTimer.start(10).on('pause', doSmth).pause(); // and so on
1

所有的参数

var myTimer = new Timer({
  tick    : 1,
  ontick  : function(ms) { console.log(ms + ' milliseconds left') },
  onstart : function() { console.log('timer started') },
  onstop  : function() { console.log('timer stop') },
  onpause : function() { console.log('timer set on pause') },
  onend   : function() { console.log('timer ended normally') }
});
1
2
3
4
5
6
7
8

所有的方法

myTimer.start(10)
.pause()
.stop()

// on可以监听的事件 tick, ontick, start, onstart, end, onend, stop, onstop, pause, onpause
myTimer.on('end', function() {
  console.log('woo-hooo! my timer ended normally')
})

myTimer.off('pause')
// 恢复默认
myTimer.off('all')
// 获得当前的状态 状态值 'initialized', 'started', 'paused', 'stopped'
myTimer.getStatus() // 'initialized'
myTimer.start(20).getStatus() // 'started'
myTimer.pause().getStatus() // 'paused'


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

getDuration() 获取剩余时间

myTimer.start(20)
// some operation that lasts for 2 seconds
myTimer.getDuration() // 18000
1
2
3

measureStart() measureStop()获取之间的执行时间

myTimer.measureStart('label1');
var a = [];
for (var i = 10000000; i >= 0; i--) {
    a.push(i * Math.random());
};
myTimer.measureStop('label1'); // 276 i.e.
1
2
3
4
5
6