一, 每个脚本,即继承自cc.Component的都自带一个Scheduler计时器
const {ccclass, property} = cc._decorator;
@ccclass
export default class DemoLocalTimer extends cc.Component {
start() {
//永久执行 0秒后执行(立即执行) , 1S执行一次
this.schedule(this.onTimer, 1, cc.macro.REPEAT_FOREVER, 0);
//10S后执行一次
this.scheduleOnce(this.onOnceTimer,10);
}
private onTimer(): void {
cc.log(`%c永久: onTimer ` , "color:#a00;");
}
private onOnceTimer(): void {
cc.log(`%c一次: onOnceTimer ` , "color:#00");
}
protected onDestroy() {
this.unschedule(this.onTimer);//remove onTimer 计时器
}
}
运行结果
二, cc.director的计时器(相当于全局)
const {ccclass, property} = cc._decorator;
@ccclass
export default class DemoTimer extends cc.Component {
private _scheduler: cc.Scheduler;
start() {
this._scheduler = cc.director.getScheduler();
this._scheduler.enableForTarget(this);//必须使用enableForTarget注册Id不然会报错
//延迟3秒后,输出1,此后每1秒输出1,重复3次。一共输出1+3次
this._scheduler.schedule(this.test1, this, 1, 3,3, false);
//延迟3秒后,输出1,此后每1秒输出1,无限重复
this._scheduler.schedule(this.test2, this, 1, cc.macro.REPEAT_FOREVER,3, false);
}
private test1(){
console.log("test1");
}
private test2(){
console.log("test2");
}
protected onDestroy(): void{
this._scheduler.unscheduleAll();//删除绑定的所有计时器
//this._scheduler.unschedule(this.test1,this);//remove test1 计时器
//this._scheduler.unschedule(this.test2,this);//remove test2 计时器
}
}
运行结果