下面講解下有哪些方法可以實現定時操作。
Schedule
這個是屬於cc.Component類中的一個方法
調度一個自定義的回調函數,如果回調函數已調度,那麼將不會重複調度它,只會更新時間間隔參數。
meta | description |
---|---|
定義於 | https:/github.com/cocos-creator/engine/blob/master/cocos2d/core/components/CCComponent.js:541 |
參數列表
callback
function The callback functioninterval
Number Tick interval in seconds. 0 means tick every frame.repeat
Number The selector will be executed (repeat + 1) times, you can use cc.macro.REPEAT_FOREVER for tick infinitely.delay
Number The amount of time that the first tick will wait before execution.
示例
var timeCallback = function (dt) {
cc.log("time: " + dt);
}
this.schedule(timeCallback, 1);
//取消
this.unschedule(timeCallback);
注意:
如果repeat不輸入的話是forever,輸入的話repeat是(repeat + 1)次。
還有當場景進入後臺或者active=false時,schedule會停止運行,當進入前臺進,再次運行。
RunAction
這個屬於cc.Node類中的方法。
ActionInterval
let timeAction = cc.sequence(cc.delayTime(30), cc.callFunc(() => {
console.log('time out');
}));
let action = timeAction.repeatForever();
action.setTag(1);
//有次數 let action = timeAction.repeat(5);
this.node.runAction(action);
this.node.stopAction(timeAction);
//this.node.stopActionByTag(1);
注意:
還有當場景進入後臺或者active=false時,Action會停止運行,當進入前臺進,再次運行。
JS原生
不多說,放碼。
this.intervalId = setInterval(() => {
this.loopCheckScene();
}, 100);
clearInterval(this.intervalId);
let timeoutId = setTimeout(() => {
console.log('time out');
}, 1000);
clearTimeout(timeoutId);
最後
希望通過講解,對新手們有所幫助。最後還是那句話,喜歡就動動手指點喜歡,關注我吧。我會不定時更新Cocos Creator教程哦~