1.scheduleUpdate
节点中有scheduleUpdate接口,通过这个接口,可以让游戏在每帧执行都执行update方法
var ScheduleUpdateLayer = cc.Layer.extend({ ???ball:null, ???ctor:function () { ???????this._super(); ???????this.scheduleUpdate(); // 开启定时器 ???????var winSize = cc.director.getWinSize(); ???????var ball = new cc.Sprite("res/item_2.png"); ???????ball.x = winSize.width/2; ???????ball.y = winSize.height/2; ???????this.addChild(ball); ???????this.ball = ball; ???????cc.eventManager.addListener({ // 监听鼠标事件 ???????????event:cc.EventListener.MOUSE, ???????????onMouseDown:function (event) { ???????????????var action = cc.moveTo(1,event.getLocation().x,event.getLocation().y); ???????????????ball.runAction(action); ???????????} ???????},this) ???}, ???update : function () { // 重写update方法 ???????console.log(this.ball.x+"---"+this.ball.y); ???}})
2. scheduleOnce
scheduleOnce和setTimeout类似,接受两个参数,第一个参数是回调函数,第二个参数是事件,scheduleOnce接受的时间以秒为单位。
节点都有scheduleOnce接口。
var ScheduleLayer = cc.Layer.extend({ ???ctor:function () { ???????this._super(); ???????this.scheduleOnce(function () { ?// 2秒后打印日志 ??????????console.log("scheduleOnce"); ???????},2); ???}})
3. schedule
schedule和setInterval类似,实现固定时间间隔不断触发某个函数的功能。node.schedul(callback, interval, repeat, delay)
interval触发间隔,以秒为单位
repeat重复次数,会执行repeat+1次
delay是第一次出发前的延迟时间,以秒为单位
如果希望schedule无限循环,可以省略后两个参数,也可以设置repeat为常量cc.REPEATE_FOREVER
this.schedule(function () { ???????????console.log("schedule"); ???????},2,cc.REPEAT_FOREVER,2);
schedule基于帧数控制,当帧频降低时,schedule会积累大量的误差
一个平衡的定时器
schedule2:function (callback,interval) { ???????var then = Date.now(); ???????interval = interval*1000; ???????this.schedule(function () { ???????????var now = Date.now(); ???????????var delta = now-then; ???????????if(delta > interval){ ???????????????then = now - (delta % interval); //如果本次触发延迟了,就让下次触发早一点来抵消误差 ???????????????callback.call(this); ???????????} ???????}.bind(this),0); // 0表示每帧触发 ???}
4. 取消定时器
- 取消scheduleUpdate ,使用 node.unscheduleUpdate()
- 取消scheduleOnce和schedule,使用node.unschedule()
var ScheduleLayer = cc.Layer.extend({ ???ctor:function () { ???????this._super(); ???????this.schedule(this.tick,1,cc.REPEAT_FOREVER,1); ???????this.tickCount = 0; ???}, ???tick:function () { ???????console.log("tick"); ???????this.tickCount++; ???????if(this.tickCount == 5){ ???????????this.unschedule(this.tick); ???????} ???}})
5.暂停/恢复定时器
node.pause(); ?//暂停node.resume(); //恢复
作者:写java的逗比叫z1
链接:http://www.jianshu.com/p/df26c8ef1671
cocos2d-js 定时器
原文地址:http://www.cnblogs.com/kefeiGame/p/7681023.html