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
1 | function startBroadcast() { |
Bind the callback
1 | function startBroadcast() { |
Use an arrow function
Arrow functions inherit this lexically from the surrounding scope and are usually the clearest TypeScript option:
1 | function startBroadcast() { |
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.