github.com/olivere/camlistore@v0.0.0-20140121221811-1b7ac2da0199/server/camlistored/ui/animation_loop.js (about) 1 /* 2 Copyright 2013 The Camlistore Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 goog.provide('cam.AnimationLoop'); 18 19 goog.require('goog.events.EventTarget'); 20 21 // Provides an easier-to-use interface around window.requestAnimationFrame(), and abstracts away browser differences. 22 // @param {Window} win 23 cam.AnimationLoop = function(win) { 24 goog.base(this); 25 26 this.win_ = win; 27 28 this.requestAnimationFrame_ = win.requestAnimationFrame || win.mozRequestAnimationFrame || win.webkitRequestAnimationFrame || win.msRequestAnimationFrame; 29 30 this.handleFrame_ = this.handleFrame_.bind(this); 31 32 this.lastTimestamp_ = 0; 33 34 if (this.requestAnimationFrame_) { 35 this.requestAnimationFrame_ = this.requestAnimationFrame_.bind(win); 36 } else { 37 this.requestAnimationFrame_ = this.simulateAnimationFrame_.bind(this); 38 } 39 }; 40 41 goog.inherits(cam.AnimationLoop, goog.events.EventTarget); 42 43 cam.AnimationLoop.FRAME_EVENT_TYPE = 'frame'; 44 45 cam.AnimationLoop.prototype.isRunning = function() { 46 return Boolean(this.lastTimestamp_); 47 }; 48 49 cam.AnimationLoop.prototype.start = function() { 50 if (this.isRunning()) { 51 return; 52 } 53 54 this.lastTimestamp_ = -1; 55 this.schedule_(); 56 }; 57 58 cam.AnimationLoop.prototype.stop = function() { 59 this.lastTimestamp_ = 0; 60 }; 61 62 cam.AnimationLoop.prototype.schedule_ = function() { 63 this.requestAnimationFrame_(this.handleFrame_); 64 }; 65 66 cam.AnimationLoop.prototype.handleFrame_ = function(opt_timestamp) { 67 if (this.lastTimestamp_ == 0) { 68 return; 69 } 70 71 var timestamp = opt_timestamp || new Date().getTime(); 72 if (this.lastTimestamp_ == -1) { 73 this.lastTimestamp_ = timestamp; 74 } else { 75 this.dispatchEvent({ 76 type: this.constructor.FRAME_EVENT_TYPE, 77 delay: timestamp - this.lastTimestamp_ 78 }); 79 this.lastTimestamp_ = timestamp; 80 } 81 82 this.schedule_(); 83 }; 84 85 cam.AnimationLoop.prototype.simulateAnimationFrame_ = function(fn) { 86 this.win_.setTimeout(function() { 87 fn(new Date().getTime()); 88 }, 0); 89 };