Tag: Eve rect infinite timeout date delay based on Dir loop
1.scheduleUpdate
The Scheduleupdate interface in the node allows the game to execute the Update method at every frame.
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 and settimeout are similar, accept two parameters, the first parameter is a callback function, the second argument is an event, and the time that Scheduleonce accepts is in seconds.
Nodes have scheduleonce interfaces.
var ScheduleLayer = cc.Layer.extend({ ctor:function () { this._super(); this.scheduleOnce(function () { // 2秒后打印日志 console.log("scheduleOnce"); },2); }})
3. Schedule
Similar to schedule and setinterval, the ability to constantly trigger a function at fixed intervals.
node.schedul(callback, interval, repeat, delay)
Interval trigger interval, in seconds
Repeat number of repetitions, will be executed repeat+1 times
Delay is the first time before departure, in seconds
If you want to schedule an infinite loop, you can omit the latter two arguments, or you can set repeat as a constant cc. Repeate_forever
this.schedule(function () { console.log("schedule"); },2,cc.REPEAT_FOREVER,2);
Schedule based on frame number control, when the frame rate is lowered, schedule will accumulate a lot of errors
A balanced timer.
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. Cancel the timer
- Cancel Scheduleupdate, use Node.unscheduleupdate ()
- Cancel Scheduleonce and schedule, using 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. Pause/Resume Timer
node.pause(); //暂停node.resume(); //恢复
To write Java's tease is called Z1
Links: http://www.jianshu.com/p/df26c8ef1671
COCOS2D-JS Timer