一、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計時器的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/gamedaybyday/p/13047328.html