Skip to content

Instantly share code, notes, and snippets.

@fleon
Created October 2, 2018 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fleon/79106be6c5ef530d37ff1b0b62be9e69 to your computer and use it in GitHub Desktop.
Save fleon/79106be6c5ef530d37ff1b0b62be9e69 to your computer and use it in GitHub Desktop.
cocos2dx custom garbage collection
import Timeout, { timeout } from 'utils/Timeout'
export default class GarbageCollector {
private static gcTimeout: Timeout
static cancel() {
if (this.gcTimeout) {
this.gcTimeout.cancel()
}
}
static schedule() {
this.gcTimeout = timeout(this.gc, 1000)
}
private static gc() {
cc.sys.garbageCollect()
}
}
import Deferred from 'utils/Deferred'
export default class Timeout<Data = null> extends Deferred {
constructor(private fn: (data?: Data) => any = () => {}, time: number, private data?: Data) {
super()
// delay cannot be zero. Minimum delay has to be 1ms.
if (!time) time = 1
cc.director.getScheduler()
.scheduleCallbackForTarget(this, this.callback, 1e10, 0, time / 1000, false)
}
callback = () => {
this.fn(this.data)
this.resolve()
this.cancel()
}
cancel() {
cc.director.getScheduler()
.unscheduleCallbackForTarget(this, this.callback)
}
}
export function timeout<Data = null>(fn: (data?: Data) => any = noop, time = 1, data?: Data): Timeout<Data> {
return new Timeout(fn, time, data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment