Scheduler

Cocos Creator provides a powerful, flexible and convenient timer component.

Using the Scheduler

  1. Start a timer

    1. this.schedule(function() {
    2. // Here this refers to component
    3. this.doSomething();
    4. }, 5);

    The above timer will be executed every 5s.

  2. A more flexible timer

    1. // time interval in seconds
    2. let interval = 5;
    3. // number of times to repeat
    4. let repeat = 3;
    5. // delay starts
    6. let delay = 10;
    7. this.schedule(function() {
    8. // Here this refers to component
    9. this.doSomething();
    10. }, interval, repeat, delay);

    The above timer will start timing after 10 seconds, and execute a callback every 5 seconds, repeating 3 times.

  3. Timer that executes only once (shortcut)

    1. this.scheduleOnce(function() {
    2. // Here this refers to component
    3. this.doSomething();
    4. }, 2);

    The timer above will execute the callback function once after two seconds, and then stop timing.

  4. Cancel a timer

    Developers can use the callback function itself to cancel the timer:

    1. this.count = 0;
    2. this.callback = function () {
    3. if (this.count == 5) {
    4. // Cancel this timer when the callback is executed
    5. // for the sixth time
    6. this.unschedule(this.callback);
    7. }
    8. this.doSomething();
    9. this.count++;
    10. }
    11. this.schedule(this.callback, 1);

Note: when the component’s timer calls the callback, the this of the callback is specified as the component itself, so this can be used directly in the callback.

Here is a list of all of the timer functions in Component:

  • schedule: start a timer
  • scheduleOnce: start a timer that is executed only once
  • unschedule: cancel a timer
  • unscheduleAllCallbacks: cancel all timers of this component

The detailed description of these APIs can be found in the API documentation.

In addition, if developers need to execute a function every frame, please add the update function directly to the Component. This function will be called every frame by default. This is described in Lifecycle Document.

Note: Node does not include timer related APIs