Jump to content

Calling setTimeout from update method


samjarman
 Share

Recommended Posts

I'm trying to add a small delay between the last of my action and moving onto the next level/state. 

 

I've tried this

setTimeout(function(){console.log("foo");   levelData.game.state.start('information');}, 1000)

but the method gets called a lot of times until phaser starts moaning. 

 

Is there a nice way to do this?

 

Link to comment
Share on other sites

Look at the Time section of phaser.io/examples

    //  Here we'll create a basic timed event. This is a one-off event, it won't repeat or loop:    //  The first parameter is how long to wait before the event fires. In this case 4 seconds (you could pass in 4000 as the value as well.)    //  The next parameter is the function to call ('fadePicture') and finally the context under which that will happen.    game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
Link to comment
Share on other sites

The update method gets called up to 60 times per second, so this isn't the place to be starting timers without at first checking to see if they're already running. Also, you should use Phaser's time events instead of setTimeout:

levelData.game.time.events.add(1000, function() {  console.log("foo");  levelData.game.state.start('information');}, this);

Put this in a function which is called once when all requirements for your end-state condition are met, and maybe hold a variable called 'levelEnded' which stops it being called again.

 

Alternatively, if you're trying to create something like a rolling delay (a bit like an idle timer, every time something happens it resets) then rather than using timers, you could set a var to game.time.now every time the player makes an action, and in the update method do something like this:

function update() {  // if the last action was more than 5 seconds ago...  if (game.time.now - lastActionTime > 5000) {    // ... do your state switch here  }}
Link to comment
Share on other sites

  • 3 years later...

Hi guys, 

 

I was attempting to add a delay to the my preloader function that boots my StartMenu. Here is a segment of my code. Any suggestions? 

 

    update: function (){
        this.ready = true;
        this.state.start('StartMenu').time.events.add(Phaser.Timer.SECOND * 4);
    }

 

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...