一 说明
1.1 当前软件环境,Windows10,Cocos Creator 2.4.8,VSCode
1.2 安装VSCode插件 Debugger for Chrome
二 关于同步和异步的区分
在我所稍微有点深入接触到的语言或IDE中,
- c/c++:CreatThread,创建线程
- go:go 创建新的goroutine
- lua/javascript:在这类脚本语言调用底层cocos2d-x机制里,都有计时器,时间间隔相关功能
- android:创建线程
中都有异步的概念。最初在windows编程的时期,典型的同步和异步的区分,就是 关于 SendMessage和PostMessage的区分。
在我的理解中,就是先调用,但后完成的函数,就是异步函数。
这里引用一张图,来源于 https://www.runoob.com/js/js-async.html,描述的比较清楚。
async-sync.png
三 关于creator中的异步函数
3.1 计时器函数
schedule:开始一个计时器
scheduleOnce:开始一个只执行一次的计时器
testSchedule: function () {
this.scheduleOnce(function() {
this.print_timestamp("定时器2");
}.bind(this), 2);
this.scheduleOnce(function() {
this.print_timestamp("定时器3");
}.bind(this), 3);
this.scheduleOnce(function() {
this.print_timestamp("定时器4");
}.bind(this), 4);
this.print_timestamp("testSchedule()");
},
print_timestamp(param){
var date = new Date();
console.log("print_timestamp(),"+param+","+date.getTime()/1000);
},
VSCode调试控制台输出结果【时间戳单位秒】:
print_timestamp(),testSchedule(),1652521098.637
print_timestamp(),定时器2,1652521100.582
print_timestamp(),定时器3,1652521101.582
print_timestamp(),定时器4,1652521102.582
3.2 动态加载资源函数 cc.loader.loadRes
testLoader: function () {
cc.loader.loadRes("sound/bgm.mp3", cc.AudioClip, function (err, clip) {
if (err) {
console.log('cc.loader.loadRes err : ', err);
} else {
this.print_timestamp("loadRes()");
return clip;
}
}.bind(this));
this.print_timestamp("testLoader()");
},
print_timestamp(param){
var date = new Date();
console.log("print_timestamp(),"+param+","+date.getTime()/1000);
},
VSCode调试控制台输出结果【时间戳单位秒】:
print_timestamp(),testLoader(),1652521516.835
print_timestamp(),loadRes(),1652521517.124
看结果,loadRes首先调用,但是后完成。
3.3 节点动作运行函数 runAction
testRunAction(){
var action1 = cc.delayTime(1);
var action2 = cc.callFunc(function(){
this.print_timestamp("action2");
}.bind(this));
var action3 = cc.moveTo(2, cc.v2(0,0)).easing(cc.easeIn(2));
var action4 = cc.callFunc(function(){
this.print_timestamp("action4");
}.bind(this));
this.tip.runAction(cc.sequence(action1, action2, action3, action4));
this.print_timestamp("testRunAction()");
},
print_timestamp(param){
var date = new Date();
console.log("print_timestamp(),"+param+","+date.getTime()/1000);
},
VSCode调试控制台输出结果【时间戳单位秒】:
print_timestamp(),testRunAction(),1652536682.203
print_timestamp(),action2,1652536683.17
print_timestamp(),action4,1652536685.17
学海无涯,错误难免,如有发现,尽请指正。
--the end