-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
44 lines (38 loc) · 940 Bytes
/
index.js
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
var inherits = require('inherits')
var EventEmitter = require('events').EventEmitter
var now = require('right-now')
var raf = require('raf')
module.exports = Engine
function Engine(fn) {
if (!(this instanceof Engine))
return new Engine(fn)
this.running = false
this.last = now()
this._frame = 0
this._tick = this.tick.bind(this)
if (fn)
this.on('tick', fn)
}
inherits(Engine, EventEmitter)
Engine.prototype.start = function() {
if (this.running)
return
this.running = true
this.last = now()
this._frame = raf(this._tick)
return this
}
Engine.prototype.stop = function() {
this.running = false
if (this._frame !== 0)
raf.cancel(this._frame)
this._frame = 0
return this
}
Engine.prototype.tick = function() {
this._frame = raf(this._tick)
var time = now()
var dt = time - this.last
this.emit('tick', dt)
this.last = time
}