1 /**
  2  * タイマー
  3  *
  4  * @class
  5  * @constructor
  6  * @param duration {Number} 効果時間(ミリ秒)
  7  * @param [params] {Object}
  8  * @param [params.isStartImmediate = false] {Boolean} すぐに開始するか
  9  * @param [params.onUpdate] {Function} 更新された
 10  * @param [params.onComplete] {Function} コールバック
 11  */
 12 WINDOW_APP.classes.Timer = function (duration, params) {
 13 	this._duration = duration;
 14 	this._onUpdate = params.onUpdate;
 15 	this._onComplete = params.onComplete;
 16 	if(params.isStartImmediate) {
 17 		this.start();
 18 	}
 19 };
 20 
 21 WINDOW_APP.classes.Timer.prototype = {
 22 
 23 	_FPS: 33.3,	//フレームレート
 24 
 25 	_duration: 1000,
 26 	_timerId: 0,	//タイマーid
 27 	_startTime: 0,
 28 	_finishTime: 0,
 29 	_onUpdate: undefined,
 30 	_onComplete: undefined,
 31 
 32 	/**
 33 	 * タイマースタート
 34 	 *
 35 	 */
 36 	start: function () {
 37 		var
 38 			me = this,
 39 			now = new Date();
 40 
 41 		if(me._duration > 0) {
 42 			me._startTime = now.getTime();	//開始時間
 43 			me._finishTime = now.getTime() + me._duration - me._FPS;	//終了時間
 44 			me._timerId = setInterval(function () {
 45 				me._interval();
 46 			}, me._FPS);
 47 		}
 48 		else {
 49 			//効果時間が0以下の場合、すぐにコールバック
 50 			me.stop();
 51 			if(me._onComplete) {
 52 				me._onComplete.apply(me._onComplete);
 53 			}
 54 		}
 55 	},
 56 
 57 	/**
 58 	 * タイマー停止
 59 	 *
 60 	 */
 61 	stop: function () {
 62 		var me = this;
 63 		if(me._timerId) {
 64 			clearInterval(me._timerId);
 65 			me._timerId = null;
 66 		}
 67 	},
 68 
 69 	/**
 70 	 * タイマーループ
 71 	 *
 72 	 */
 73 	_interval: function () {
 74 		var
 75 			me = this,
 76 			now = new Date();
 77 
 78 		if(me._onUpdate) {
 79 			me._onUpdate.apply(me, [now.getTime() - me._startTime]);
 80 		}
 81 
 82 		if(now.getTime() >= me._finishTime) {
 83 			clearInterval(me._timerId);
 84 			me._timerId = null;
 85 			setTimeout(function () {
 86 				if(me._onUpdate) {
 87 					me._onUpdate.apply(me._onUpdate, [now.getTime() - me._startTime]);
 88 				}
 89 
 90 				if(me._onComplete) {
 91 					me._onComplete.apply(me._onComplete);
 92 				}
 93 			},  me._FPS);
 94 		}
 95 	}
 96 };