好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解CocosCreator中几种计时器的使用方法

一、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计时器的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/gamedaybyday/p/13047328.html

查看更多关于详解CocosCreator中几种计时器的使用方法的详细内容...

  阅读:53次