1. setTimeOut
Print abc in 3 seconds. Only execute once.
setTimeout(()=>{("abc"); }, 3000);
Delete the timer, and the abc will not be output after 3 seconds.
let timeIndex; timeIndex = setTimeout(()=>{("abc"); }, 3000); clearTimeout(timeIndex);
This is written in the test function, and this output is a Window object
@ccclass export default class Helloworld extends { private a = 1; start() { setTimeout(, 3000); } private test(){ (); //Output undefined (this); //Window } }
Use arrow functions
@ccclass export default class Helloworld extends { private a = 1; start() { setTimeout(()=>{()}, 3000); } private test(){ (); //Output 1 (this); //Helloworld } }
2. setInterval
After 1 second, output abc, repeat execution, and an abc will be output every second.
setInterval(()=>{("abc"); }, 1000);
Delete the timer and no abc is output again.
let timeIndex; timeIndex = setInterval(()=>{("abc"); }, 1000); clearInterval(timeIndex);
3. Schedule
Every inherited comes with this timer
schedule(callback: Function, interval?: number, repeat?: number, delay?: number): void;
After 3 seconds of delay, output abc, and then output abc every 1 second, repeating 5 times. So in the end, 5+1 abc will be output.
(()=>{("abc")},1,5,3);
Delete schedule (If you want to delete, you can no longer use anonymous functions, you must be able to access the function you want to delete)
private count = 1; start() { (,1,5,3); (); } private test(){ (); }
Global schedule
It's equivalent to a global timer, on top. Note that enableForTarget() must be called to register the id, otherwise an error will be reported.
start() { let scheduler: = (); (this); //After delay of 3 seconds, output 1, and then output 1 every 1 second, repeat 3 times. A total of 1+3 outputs (this.test1, this, 1, 3,3, false); //After delay of 3 seconds, output 1, and then output 1 every 1 second, repeat infinitely (this.test2, this, 1, .REPEAT_FOREVER,3, false); } private test1(){ ("test1"); } private test2(){ ("test2"); }
//Delete the timer(this.test1, this);
The above is a detailed explanation of how to use several timers in CocosCreator. For more information about CocosCreator timers, please follow my other related articles!