CocosCreator 计时器

setTimeout

  • setTimeout 是HTML中的方法,用法与之相同。
  • 该方法用于延迟一定时间后执行某个操作。
  • 该方法有两个参数,第一个参数是一个函数,即执行的操作;第二个参数是一个整数,即以毫秒为单位的延迟时间

setInterval

  • 与 setTimeout 相同,只不过它会按照指定的时间间隔重复执行代码,直至间歇调用被取消或页面被卸载。

cc.Scheduler

  • 此组件时Cocos中独特的一个组件,可以综合上述两种功能
component.schedule(function() {
     // 这里的 this 指向 component
     this.doSomething();
 }, 5);

这个计时器将每隔 5s 执行一次。

// 以秒为单位的时间间隔
 var interval = 5;
 // 重复次数
 var repeat = 3;
 // 开始延时
 var delay = 10;
 component.schedule(function() {
     // 这里的 this 指向 component
     this.doSomething();
 }, interval, repeat, delay);

在10秒后开始计时,每5秒执行一次回调,重复3次。

  • 由上面两个例子,我们知道,schedule 函数是在 component 结构上的(并不是Node 结构上),函数中的 this指向这个组件 component
  • Component 中所有关于计时器的函数
    • schedule:开始一个计时器
    • scheduleOnce:开始一个只执行一次的计时器
    • unschedule:取消一个计时器
    • unscheduleAllCallbacks:取消这个组件的所有计时器
component.scheduleOnce(function() {
     // 这里的 this 指向 component
     this.doSomething();
 }, 2);

上面的计时器将在两秒后执行一次回调函数,之后就停止计时。

 this.count = 0;
 this.callback = function () {
     if (this.count === 5) {
         // 在第六次执行回调时取消这个计时器
         this.unschedule(this.callback);
     }
     this.doSomething();
     this.count++;
 }
 component.schedule(this.callback, 1);

猜你喜欢

转载自blog.csdn.net/qq_43575267/article/details/88910712