CocosCreatorschedule计时器使⽤
代码顺序问题
计时器可以理解为⼀个纯内部循环的函数,不影响后⾯代码的运⾏
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,循环体是否执⾏完毕并不影响其他代码运⾏。
计时器取消schedule用法及搭配
官⽅⽂档:
this.callback = function () {
if (unt === 5) {
// 在第六次执⾏回调时取消这个计时器
this.unschedule(this.callback);
}
this.doSomething();
}
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的传⼊正确。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。