计时器可以理解为一个纯内部循环的函数,不影响后面代码的运行
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
,循环体是否执行完毕并不影响其他代码运行。
this.count = 0;
this.callback = function () {
if (this.count === 5) {
// 在第六次执行回调时取消这个计时器
this.unschedule(this.callback);
}
this.doSomething();
this.count++;
}
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的传入正确。
原文:https://www.cnblogs.com/m0r3/p/14660209.html