UNPKG

raf-loop

Version:

a minimal requestAnimationFrame render loop

44 lines (38 loc) 940 B
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 }