详解CocosCreator中几种计时器的使用方法
- 作者: 命中助腚
- 来源: 51数据库
- 2021-08-14
一、settimeout
3秒后打印abc。只执行一次。
settimeout(()=>{console.log("abc"); }, 3000);
删除计时器,3秒后不会输出abc。
let timeindex;
timeindex = settimeout(()=>{console.log("abc"); }, 3000);
cleartimeout(timeindex);
settimeout这样写,test函数中输出的this是window对象
@ccclass
export default class helloworld extends cc.component {
private a = 1;
start() {
settimeout(this.test, 3000);
}
private test(){
console.log(this.a); //输出undefined
console.log(this); //window
}
}
使用箭头函数
@ccclass
export default class helloworld extends cc.component {
private a = 1;
start() {
settimeout(()=>{this.test()}, 3000);
}
private test(){
console.log(this.a); //输出1
console.log(this); //helloworld
}
}
二、setinterval
1秒后输出abc,重复执行,每秒都会输出一个abc。
setinterval(()=>{console.log("abc"); }, 1000);
删除计时器,不会再输出abc。
let timeindex;
timeindex = setinterval(()=>{console.log("abc"); }, 1000);
clearinterval(timeindex);
三、schedule
每个继承cc.component的都自带了这个计时器
schedule(callback: function, interval?: number, repeat?: number, delay?: number): void;
延迟3秒后,输出abc,此后每隔1秒输出abc,重复5次。所以最终会输出5+1次abc。
this.schedule(()=>{console.log("abc")},1,5,3);
删除schedule(若要删除,则不能再使用匿名函数了,得能访问到要删除的函数)
private count = 1;
start() {
this.schedule(this.test,1,5,3);
this.unschedule(this.test);
}
private test(){
console.log(this.count);
}
全局的schedule
相当于一个全局的计时器吧,在cc.director上。注意必须调用enablefortarget()来注册id,不然会报错。
start() {
let scheduler:cc.scheduler = cc.director.getscheduler();
scheduler.enablefortarget(this);
//延迟3秒后,输出1,此后每1秒输出1,重复3次。一共输出1+3次
scheduler.schedule(this.test1, this, 1, 3,3, false);
//延迟3秒后,输出1,此后每1秒输出1,无限重复
scheduler.schedule(this.test2, this, 1, cc.macro.repeat_forever,3, false);
}
private test1(){
console.log("test1");
}
private test2(){
console.log("test2");
}
//删除计时器 scheduler.unschedule(this.test1, this);
以上就是详解cocoscreator中几种计时器的使用方法的详细内容,更多关于cocoscreator计时器的资料请关注其它相关文章!
推荐阅读
