版本: 3.7
在cocosCreator中, Node
不包含定时器相关的API, 定时器主要用在组件中。
常用的接口主要有如下几类:
update/lateUpdate
schedule/scheduleOnce
setTimeout/setInterval
生命周期提供的回调接口,每帧都会被执行,多用于更新对象的状态,不推荐处理太过复杂的逻辑:
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;
@ccclass("updatetest")
export class updatetest extends Component {
// onLoad之后被调用,每帧都会被执行,用于更新对象状态
update (deltaTime: number) {
this.node.setPosition(0.0,40.0*deltaTime,0.0);
}
// 在update之后被调用,每帧都会执行
lateUpdate() {
console.log("lateUpdate...");
}
}
组件定时器,使用灵活。参考:计时器 。官方提供的主要接口有:
/*
schedule定时器,使用灵活,强大
* callback 回调接口
* interval 时间间隔,以秒为单位,默认为0
* repeat 重复次数,会被执行(repeat+1)次,默认为macro.REPEAT_FOREVER表示无限重复
* delay 延迟时间,以秒为单位,默认为0表示立即调用
*/
schedule(callback: any, interval?: number, repeat?: number, delay?: number):
/*
scheduleOnce执行一次的定时器
* callback 回调接口
* delay 延迟时间,以秒为单位,默认为0表示立即调用
*/
scheduleOnce(callback: any, delay?: number): void;
// 根据回调取消一个计时器
unschedule(callback_fn: any): void;
// 取消组件中的所有计时器
unscheduleAllCallbacks(): void;
注意:定时器结束后要记得unschedule
取消,避免内存泄漏。
具体的示例:
import { _decorator, Component, Node } from 'cc';
const { ccclass, property, help } = _decorator;
@ccclass('uiScene_schedule')
export class uiScene_schedule extends Component {
private _onceTimer = null;
onLoad() {
this._repeatCount = 0;
}
start () {
// schedule
let interval = 1;
let repeat = macro.REPEAT_FOREVER;
let delay = 0;
this.schedule(this.onScheduleEvent, interval, repeat, delay);
// scheduleOnce
let delayTime = 2;
this._onceTimer = this.scheduleOnce(function() {
console.log("sheduleOnce执行一次定时器")
}, delayTime);
}
onScheduleEvent () {
this._repeatCount += 1;
console.log("schedule重复次数为:" + this._repeatCount);
}
onDestroy() {
this.unschedule(this.onScheduleEvent);
this.unschedule(this._onceTimer);
}
}
javaScript中常用的定时器函数,在typeScript中也可以使用。
/*
@func: 用于指定的时间后执行回调
@param: 回调接口
@param: 延迟时间,单位为毫秒,默认为0
@param: 传递给回调接口的附加参数
@return: 返回timeout ID
*/
setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;
// 根据timeout ID回收定时器
clearTimeout(id: number | undefined): void;
/*
@func: 用于每隔一段时间执行回调
@param: 回调接口
@param: 时间间隔,单位为毫秒,默认为0
@param: 传递给回调接口的附加参数
@return: 返回interval ID
*/
setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;
// 根据interval ID回收定时器
clearInterval(id: number | undefined): void;
具体的示例:
@ccclass('uiScene_schedule')
@help("https://docs.cocos.com/creator/manual/zh/scripting/scheduler.html")
export class uiScene_schedule extends Component {
private _outTimer = null;
private _interTimer = null;
onLoad(): void {
this._intercount = 0;
}
start () {
this._outTimer = setTimeout(() => {
this.label_3.string = "setTimeout";
}, 1000);
this._interTimer = setInterval(() => {
this._intercount ++;
this.label_4.string = "setInterval:" + this._intercount;
}, 1000);
}
onDestroy() {
// 清空定时器
clearTimeout(this._outTimer);
clearInterval(this._interTimer);
}
}
待定…