在 Cocos Creator 中,我們為元件提供了友善的計時器,這個計時器源自于 Cocos2d-x 中的
cc.Scheduler
,我們将它保留在了 Cocos Creator 中并适配了基于元件的使用方式。
也許有人會認為
setTimeout
和
setInterval
就足夠了,開發者當然可以使用這兩個函數,不過我們更推薦使用計時器,因為它更加強大靈活,群組件也結合得更好!
下面來看看它的具體使用方式:
- 開始一個計時器
上面這個計時器将每隔 5s 執行一次。component.schedule(function() { // 這裡的 this 指向 component this.doSomething(); }, 5);
- 更靈活的計時器
上面的計時器将在10秒後開始計時,每5秒執行一次回調,重複3次。// 以秒為機關的時間間隔 var interval = 5; // 重複次數 var repeat = 3; // 開始延時 var delay = 10; component.schedule(function() { // 這裡的 this 指向 component this.doSomething(); }, interval, repeat, delay);
- 隻執行一次的計時器(快捷方式)
上面的計時器将在兩秒後執行一次回調函數,之後就停止計時。component.scheduleOnce(function() { // 這裡的 this 指向 component this.doSomething(); }, 2);
-
取消計時器
開發者可以使用回調函數本身來取消計時器:
this.count = 0; this.callback = function () { if (this.count === 5) { // 在第六次執行回調時取消這個計時器 this.unschedule(this.callback); } this.doSomething(); this.count++; } component.schedule(this.callback, 1);
下面是 Component 中所有關于計時器的函數:
- schedule:開始一個計時器
- scheduleOnce:開始一個隻執行一次的計時器
- unschedule:取消一個計時器
- unscheduleAllCallbacks:取消這個元件的所有計時器
這些 API 的較長的描述都可以在 Component API 文檔中找到。
除此之外,如果需要每一幀都執行一個函數,請直接在 Component 中添加
update
函數,這個函數将預設被每幀調用,這在生命周期文檔中有較長的描述。
注意: cc.Node
不包含計時器相關 API
cc.Node