Tips: Typescript decorator for frame rate limitation

Are you tired of writing this every time you want to limit the call of a function of one of your sprites?

private nextActivability = 0;
private activabilityRate = 500;

//...

limitedMethod() {
    if (this.scene.time.now > this.nextActivability) {
        this.nextActivability = this.scene.time.now + this.activabilityRate;

        // do limited stuff
    }
}

Below a tyepscript decorator I use:

const frameRate = (rate: number) => (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
	const original = descriptor.value;
	let nextActivability = 0;
  
	descriptor.value = function (...args) {
		const now = new Date().getTime();
		if (now > nextActivability) {
			nextActivability = now + rate;
			original.call(this, ...args);
		}
	};
};

export default frameRate;

You can, then, fix the previous code like that:

// no more specific fields

@frameRate(500)
limitedMethod() {
    // do limited stuff
}

You just have to add a property into your tsconfig.json

{
  "compilerOptions": {
    //...
    "experimentalDecorators": true,
    //...
  },
}

What do you think about? :slight_smile: