參考:
一 setTimeOut
二 setInterval
三 Schedule (推薦用引擎提供的計時器,功能多些,銷毀時還能自動移除)
一 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);