简体   繁体   中英

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 animation is still displaying (setInterval is still executing) the setInterval is stacking up in the event stack or that is what I found out thus either crushing my game or running twice as fast (the animation). My question is is there any way to prevent event stacking? I do not want the setInterval to stack up on the previous setInterval and so on. I know that I could use clearInterval function like so:

  var timerInterval = setInterval(drawPlayerRunning, 50);
  clearInterval(timerInterval);

but it does not really work as I want it to, because what if user clicks many times while the function is still is executing, the clearInterval will only get rid of last event of the event stack leaving all the previous ones still in the "game". Any idea how to prevent this event stack up, or at least removing them efficiently?

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

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

  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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM