Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Created November 4, 2020 14:07
Show Gist options
  • Save takumifukasawa/be22c2c978ee8f9175f16cba4d5a63cf to your computer and use it in GitHub Desktop.
Save takumifukasawa/be22c2c978ee8f9175f16cba4d5a63cf to your computer and use it in GitHub Desktop.
typescript: singleton of ticker.
type Func = (time: number, deltaTime?: number) => void;
/**
* rafを管理するクラス。実質、singletonとして使う
*
* @class Ticker
*/
class Ticker {
private funcs: Func[];
private timerId: number | null;
private beforeTime: number | null;
public constructor() {
this.funcs = [];
this.timerId = null;
this.beforeTime = null;
}
/**
* listenerを追加
*
* @param {Func} func
* @memberof Ticker
*/
public add(func: Func) {
this.funcs.push(func);
}
/**
* listenerを削除
*
* @param {Func} func
* @memberof Ticker
*/
public remove(func: Func) {
const index = this.funcs.indexOf(func);
if (index > -1) {
this.funcs.splice(index, 1);
}
}
/**
* 全てのlistenerを削除
*
* @memberof Ticker
*/
public removeAll() {
this.funcs = [];
}
/**
* currentTime は performance.now と同値
*
* @private
* @param {number} currentTime
* @returns
* @memberof Ticker
*/
private tick(currentTime: number) {
// for debug
// console.log("[Ticker]", this, currentTime, this.funcs.length);
// 最初の1フレームはスキップ
if (!this.beforeTime) {
this.beforeTime = currentTime;
this.timerId = window.requestAnimationFrame(this.tick.bind(this));
return;
}
const deltaTime = currentTime - this.beforeTime;
this.funcs.forEach((func) => func(currentTime, deltaTime));
this.beforeTime = currentTime;
this.timerId = window.requestAnimationFrame(this.tick.bind(this));
}
/**
* rafを開始する
*
* @memberof Ticker
*/
public start() {
this.stop();
// for debug
// console.log("[Ticker] start");
this.timerId = window.requestAnimationFrame(this.tick.bind(this));
}
/**
* rafを停止する
*
* @memberof Ticker
*/
public stop() {
// for debug
// console.log("[Ticker] stop");
if (this.timerId) {
window.cancelAnimationFrame(this.timerId);
}
this.beforeTime = null;
}
}
export default new Ticker();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment