[Solved] How to schedule a function call at random time gaps?

[Solved] How to schedule a function call at random time gaps?
0.0 0


Hi I am looking at this: CocosLearning Scheduling and I am interested in scheduling a function call forever with a time gap between calls. But I do not want a fixed time gap, I am trying to figure out how I can call it at random times.

So I am using Math.floor((Math.random() * 3) + 1) to generate a random number between 1-3 seconds and I would like to use that to schedule the call.

Logic behind this:

  1. set time using Match.random()
  2. countdown the time (in seconds) till 0 then call function
  3. set time again (new random time) and countdown to call function again
  4. repeat forever

Is there a way to do that?

this.schedule( this.UpdateFunction, 1.0 );

UpdateFunction: function( dt ) {
  // code to run

But I don’t want the 1.0 to be a fixed number.


I use something like

ctor:function() {
ScheduleRandomTime:function() {
  this.scheduleOnce(this.UpdateFunction, Math.floor((Math.random() * 3) + 1));
UpdateFunction:function() {

  // do stuff

Basically, use scheduleOnce to schedule the function you want called and then re-use scheduleOnce whenever the function is called. Don’t know if there’s a better way, but it works for me.


uhhh I love you! Thank you so much haha!!!

Though the scheduleOnce didn’t work for me, I had to use schedule in order to get it to run more than once. It would run the UpdateFunction once but then that was it, even though it called scheduleOnce again, it didn’t run it.


Did you remember to called unschedule before calling scheduleOnce?


I double checked that.


How about using an action sequence consisting of a delay action and a function call action. The function to be called does stuff, creates the same sequence again and starts over.

  • No fancy schedulers needed(no scheduling/unscheduling logic)
  • Can be randomized at every call
  • Can repeat forever
  • Can easily be paused/resumed/stopped/(re-)started


Can you give a example. I was trying a few examples yesteray with no luck ?