在微信小程序开发中,由于用到动画效果,所以就大致了解了setTimeout,结果在使用中遇到一些情况,经过验证,及通过查看网上几篇帖子,知道自己错在哪了,特意贴出其中的部分代码,望能帮助大家避免进坑。嘿嘿,
submit_to_top:function(){
const that=this;/*定时器里使用的参数变量定义时必须加const关键字,否则报错*/
that.data.count1 = that.data.count1 + that.data.count2;
console.log('-1')
that.data.count2 =0;
if (that.data.count1>0){
that.data.count1_display=true;
that.animation_fun_go();//调用动画
}
/*设置定时器*/
setTimeout(function () {
that.setData(that.data);
that.setData({ animation_pic_display: 'none', way:'step-start'});
console.log('0')/*打印输出验证信息*/
that.setData({ x: that.data.x_back, y: that.data.y_back, time: that.data.time_back});
that.animation_fun_go();/*执行动画*/
console.log('1')
setTimeout(function(){ /*又设置了一个定时器,因为上面的动画还没执行完,下面的代码就已经把数据更新了,容易造成数据不同步,达不到设计的效果*/
console.log('2')
that.setData({ animation_pic_display: 'block', way:'ease-out'});
that.setData({ x: that.data.x_go, y: that.data.y_go, time: that.data.time_go });
console.log('3')
},30)
console.log('4')
}, 240)/*定时器240毫秒后,执行括号内部代码*/
console.log('5')
}
验证的参数的输出顺序:-1、5、0、1、4、2、3
注:
setTimeout属于异步执行函数,遇到setTimeout会将该函数放入等待队列,等待当前主程序执行完毕后开始执行setTimeout。
上述代码块中,涉及到定时器的嵌套,在定时器内部执行时仍遵循上述规则