Skip to content Skip to sidebar Skip to footer

Prevent Javascript Setinterval Function Stacking Up

I have a function that runs on a click event that uses javascript's setIterval for some of my animations (i'm doing a game) so the problem is that if a user clicks while the animat

Solution 1:

You can create a flag that monitors the interval state: 1)

var isIntervalInProgress = false;
setInterval(function()
{
  if ( isIntervalInProgress )
    returnfalse;

  isIntervalInProgress = true;

  drawPlayerRunning();

  isIntervalInProgress = false;

}, 50);

or just a timeout that will run itself once it's finished: 2)

var func = function()
{
  setTimeout(function()
  {
    drawPlayerRunning();
    func();
  }, 50)
}

whichever you like

Solution 2:

You want to use requestAnimationFrame. It is designed with games in mind, and if your code happens to be too slow, it will reduce your frame rate accordingly (from 60 fps to 30 fps for instance). But it won't stack-up events.

Edit: Sorry, I think I misunderstood your question. Let me try again.

You should have only one draw function which is called every few milliseconds (set the interval up with requestAnimationFrame(draw)).

A click should not add a new interval, but rather create a floatingAnimation object and add it to the list of objects to render. All animation objects will be rendered by the draw function everytime the browser calls draw. In the arguments passed to draw, there will be a timestamp. Use this timestamp minus the creation date of floatingAnimation to determine how to draw the floating thing above the character.

Post a Comment for "Prevent Javascript Setinterval Function Stacking Up"