1 | module.exports = raf
|
2 |
|
3 | var EE = require('events').EventEmitter
|
4 | , _raf = require('./polyfill.js')
|
5 | , global = require('./window.js')
|
6 | , now = global.performance && global.performance.now ? function() {
|
7 | return performance.now()
|
8 | } : Date.now || function () {
|
9 | return +new Date()
|
10 | }
|
11 |
|
12 |
|
13 | function raf(el, tick) {
|
14 | var now = raf.now()
|
15 | , ee = new EE
|
16 |
|
17 | if(typeof el === 'function') {
|
18 | tick = el
|
19 | el = undefined
|
20 | }
|
21 |
|
22 | ee.pause = function() { ee.paused = true }
|
23 | ee.resume = function() {
|
24 | if(ee.paused) {
|
25 | _raf.call(global, iter, el)
|
26 | }
|
27 | ee.paused = false
|
28 | }
|
29 |
|
30 | _raf.call(global, iter, el)
|
31 |
|
32 | if(tick) {
|
33 | ee.on('data', function(dt) {
|
34 | tick(dt)
|
35 | })
|
36 | }
|
37 |
|
38 | return ee
|
39 |
|
40 | function iter(timestamp) {
|
41 | var _now = raf.now()
|
42 | , dt = _now - now
|
43 |
|
44 | now = _now
|
45 |
|
46 | if(!ee.paused) {
|
47 | ee.emit('data', dt)
|
48 | }
|
49 |
|
50 |
|
51 |
|
52 | if(!ee.paused) {
|
53 | _raf.call(global, iter, el)
|
54 | }
|
55 | }
|
56 | }
|
57 |
|
58 | raf.polyfill = _raf
|
59 | raf.now = now
|
60 |
|