GitHub Documentation

'random' clock timing

  • I'm trying to create some 'bot' players in my game (controlled server-side) that act at 'random' times.
    My concept was to fire a clock.setTimeout() with a random time, that calls the 'botActions' function, and at the end of that function calls itself again using another setTimeout with a different 'random' time.
    However, within the first this.clock.setTimeout, I can't seem to access this.clock.setTimeout... "this" is undefined...
    Scope issue, I assume...? Is there a more 'proper' way to accomplish this?

    without random time

            console.log("bot clock tick:", data);
            this.clock.setTimeout(this.botUpdate, 1000, {botID : data.botID});

    this.clock.setTimeout(this.botUpdate, 1000, {botID : data.botID});
    TypeError: Cannot read property 'setTimeout' of undefined

  • administrator

    Hi @davidhoare, welcome!

    This is the classical mistake regarding the this scope in JavaScript, no worries, everyone's been there! Here's a related discussion in the forum.

    To preserve the this scope in JavaScript, you can either use this.botUpdate.bind(this), or create an arrow function.


    // using Function.prototype.bind
    this.clock.setTimeout(this.botUpdate.bind(this), 1000, {botID : data.botID});
    // using arrow functions (block)
    this.clock.setTimeout(() => {
    }, 1000, {botID : data.botID});
    // using arrow functions (single line; shorthand)
    this.clock.setTimeout(() => this.botUpdate(), 1000, {botID : data.botID});

    Hope this helps! Happy holidays!


© 2021 Lucid Sight, Inc