详解CocosCreator中几种计时器的使用方法
更新时间:2021年04月16日 15:26:11 作者:gamedaybyday
这篇文章主要介绍了CocosCreator中几种计时器的使用方法,推荐使用schedule,功能多些,销毁时还能自动移除
一、setTimeOut
3秒后打印abc。只执行一次。
1 | setTimeout(()=>{console.log( "abc" ); }, 3000); |
删除计时器,3秒后不会输出abc。
1 2 3 | let timeIndex; timeIndex = setTimeout(()=>{console.log( "abc" ); }, 3000); clearTimeout(timeIndex); |
setTimeout这样写,test函数中输出的this是Window对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @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 } } |
使用箭头函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @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。
1 | setInterval(()=>{console.log( "abc" ); }, 1000); |
删除计时器,不会再输出abc。
1 2 3 | let timeIndex; timeIndex = setInterval(()=>{console.log( "abc" ); }, 1000); clearInterval(timeIndex); |
三、Schedule
每个继承cc.Component的都自带了这个计时器
1 | schedule(callback: Function, interval?: number, repeat?: number, delay?: number): void; |
延迟3秒后,输出abc,此后每隔1秒输出abc,重复5次。所以最终会输出5+1次abc。
1 | this .schedule(()=>{console.log( "abc" )},1,5,3); |
删除schedule(若要删除,则不能再使用匿名函数了,得能访问到要删除的函数)
1 2 3 4 5 6 7 8 9 10 11 12 | 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,不然会报错。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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" ); } |
1 2 | //删除计时器 scheduler.unschedule( this .test1, this ); |
以上就是详解CocosCreator中几种计时器的使用方法的详细内容,更多关于CocosCreator计时器的资料请关注脚本之