代碼順序問題
計時器可以理解為一個純內部循環的函數,不影響后面代碼的運行
inSys(){
if(!this.isRunning){//判斷計時器是否running running則不執行
this.isRunning = true; //執行后第一時間切換為running狀態
if(this.State){
cc.log(this.State);
this.schedule(this.loopbody,1);
this.isRunning = false;
}
else{
cc.log(this.State)
this.schedule(this.loopbody,1);
this.isRunning = false;
}
}
},
update(dt){
this.inSys();
}
如上代碼執行后並不會在循環體結束后(內部有跳出函數)才執行切換running。而是單獨執行的循環體,然后立即按順序執行this.isRunning = false
,循環體是否執行完畢並不影響其他代碼運行。
計時器取消
- 官方文檔:
this.count = 0; this.callback = function () { if (this.count === 5) { // 在第六次執行回調時取消這個計時器 this.unschedule(this.callback); } this.doSomething(); this.count++; } component.schedule(this.callback, 1);
- 踩坑使用(無法跳出計時器):
loopSys(){ this.callback = function(){ ... this.unschedule(this.callback) ... } this.schedule(this.callback(),1) } update(dt){ this.loopSys() }
- 解決:
loopBody(){ ... this.unschedule(this.loopBody()); ... } //計時器內部的循環體 對應上面的callback函數 loopSys(){ ... this.schedule(this.loopBody()); ... } //計時器調用函數 update(dt){ this.loopSys(); } //循環調用計時器調用函數
原理分析
this.unschedule(callback, target)是需要兩個參數來指定需要暫停的定時器對象。callback 必須是與this.schedule中的回調一樣,匿名函數不行。target則是schedule的環境對象,這兩個如有差異都不能正常停止schedule。
錯誤使用中的直接調用callback回調函數的時候為匿名函數,返回的是一個新的函數對象,用了一個loopBody來對內部循環函數命名,指定unschedule的傳入正確。