Cocos Creator Timer this Binding: setTimeout, setInterval, bind and Arrows
When a traditional function is passed directly to setTimeout or setInterval, it is invoked without the original object’s method-call context. Its this therefore does not reliably refer to the component instance.
Capture the Instance
Bind the Callback
Use an Arrow Function
Arrow functions inherit this lexically from the surrounding scope and are usually the clearest TypeScript option:
How JavaScript Chooses this
- A function invoked with
newreceives the newly created object. call,apply, andbindexplicitly supply the receiver.- A method call such as
obj.foo()usesobjas the receiver. - A plain function call uses
undefinedin strict mode and may use the global object in older non-strict behavior. - An arrow function does not create its own
this; it inherits the surrounding value.
Store the timer ID and clear it when the Cocos Creator component is disabled or destroyed, or use the component’s schedule/unschedule APIs for lifecycle-aware timers.